| id | chat_gpt_response | question | badsmell_base | bad_smell_gpt | found_any | valid_bad_smell | bad_smell_in_base | bad_smell_not_in_the_base | bad_smell_not_found | index | index_base | url_github | nr_question | id_source_code | id_base | severity |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2380 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 14337 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2380 | 14337 | minor |
| 2236 | */ NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
long method | f | f | f | long method | 0 | 13611 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 2236 | 13611 | minor | ||
| 2158 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13316 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 2 | 2158 | 13316 | minor |
| 1709 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 11762 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 1 | 1709 | 11762 | major |
| 416 | { "message": "YES, I found bad smells", "bad smells found": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; private final AbstractPathConfiguration classpathConfiguration; private final ClassLoaderConfiguration classLoaderConfiguration; private final boolean isForkRequested; private final boolean isInForkedVm; public StartupConfiguration( @Nonnull String providerClassName, @Nonnull AbstractPathConfiguration classpathConfiguration, @Nonnull ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } public boolean isProviderMainClass() { return providerClassName.endsWith( "#main" ); } public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) { return new StartupConfiguration( providerClassName, classpathConfiguration, classLoaderConfiguration, true, true ); } public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } @Deprecated public boolean useSystemClassLoader() { // todo; I am not totally convinced this logic is as simple as it could be return classLoaderConfiguration.isUseSystemClassLoader() && ( isInForkedVm || isForkRequested ); } public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } public String getProviderClassName() { return providerClassName; } public String getActualClassName() { return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; } /** * Strip any of a supplied String from the end of a String. * * If the strip String is {@code null}, whitespace is * stripped. * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ private static String stripEnd( String str, String strip ) { if ( str == null ) { return null; } int end = str.length(); if ( strip == null ) { while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) { end--; } } else { while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) { end--; } } return str.substring( 0, end ); } public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } public boolean isShadefire() { return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); } public void writeSurefireTestClasspathProperty() { getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 4224 | https://github.com/apache/maven-surefire/blob/e57f76c7e858dbbaac6be4cbcd16e215de10b064/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java/#L29-L140 | 1 | 416 | 4224 | minor |
| 1286 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | blob, feature envy | t | t | f | blob, feature envy | data class | 0 | 10611 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 1286 | 10611 | critical |
| 2555 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14825 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 2555 | 14825 | major |
| 906 | { "output": "YES, I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 8195 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 | 1 | 906 | 8195 | minor |
| 5261 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14710 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 5261 | 14710 | minor |
| 2667 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15204 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 2667 | 15204 | major |
| 1151 | YES I found bad smells the bad smells are: 1. Duplicated code 2. Long methods 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
blob | Duplicated code2 Long methods3 Feature envy | t | f | f | . Duplicated code2. Long methods3. Feature envy | blob | 0 | 10132 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 1151 | 10132 | major |
| 1091 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Collection collectBasePaths(Iterable targets) { return StreamSupport.stream(targets.spliterator(), false) .map(BuildTarget::getBasePath) .collect(ImmutableSet.toImmutableSet()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9728 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/core/model/impl/InMemoryBuildFileTree.java/#L71-L75 | 1 | 1091 | 9728 | major |
| 3588 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7922 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 3588 | 7922 | minor | ||
| 436 | {"answer":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JpegRewriter extends BinaryFileParser { private static final ByteOrder JPEG_BYTE_ORDER = ByteOrder.BIG_ENDIAN; private static final SegmentFilter EXIF_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isExifSegment(); } }; private static final SegmentFilter XMP_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isXmpSegment(); } }; private static final SegmentFilter PHOTOSHOP_APP13_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isPhotoshopApp13Segment(); } }; /** * Constructor. to guess whether a file contains an image based on its file * extension. */ public JpegRewriter() { setByteOrder(JPEG_BYTE_ORDER); } protected static class JFIFPieces { public final List pieces; public final List segmentPieces; public JFIFPieces(final List pieces, final List segmentPieces) { this.pieces = pieces; this.segmentPieces = segmentPieces; } } protected abstract static class JFIFPiece { protected abstract void write(OutputStream os) throws IOException; @Override public String toString() { return "[" + this.getClass().getName() + "]"; } } protected static class JFIFPieceSegment extends JFIFPiece { public final int marker; private final byte[] markerBytes; private final byte[] segmentLengthBytes; private final byte[] segmentData; public JFIFPieceSegment(final int marker, final byte[] segmentData) { this(marker, ByteConversions.toBytes((short) marker, JPEG_BYTE_ORDER), ByteConversions.toBytes((short) (segmentData.length + 2), JPEG_BYTE_ORDER), segmentData); } JFIFPieceSegment(final int marker, final byte[] markerBytes, final byte[] segmentLengthBytes, final byte[] segmentData) { this.marker = marker; this.markerBytes = markerBytes; this.segmentLengthBytes = segmentLengthBytes; this.segmentData = segmentData; // TODO clone? } @Override public String toString() { return "[" + this.getClass().getName() + " (0x" + Integer.toHexString(marker) + ")]"; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(segmentLengthBytes); os.write(segmentData); } public boolean isApp1Segment() { return marker == JpegConstants.JPEG_APP1_MARKER; } public boolean isAppSegment() { return marker >= JpegConstants.JPEG_APP0_MARKER && marker <= JpegConstants.JPEG_APP15_MARKER; } public boolean isExifSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.EXIF_IDENTIFIER_CODE)) { return false; } return true; } public boolean isPhotoshopApp13Segment() { if (marker != JpegConstants.JPEG_APP13_MARKER) { return false; } if (!new IptcParser().isPhotoshopJpegSegment(segmentData)) { return false; } return true; } public boolean isXmpSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.XMP_IDENTIFIER)) { return false; } return true; } public byte[] getSegmentData() { return segmentData; // TODO clone? } } static class JFIFPieceImageData extends JFIFPiece { private final byte[] markerBytes; private final byte[] imageData; JFIFPieceImageData(final byte[] markerBytes, final byte[] imageData) { super(); this.markerBytes = markerBytes; this.imageData = imageData; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(imageData); } } protected JFIFPieces analyzeJFIF(final ByteSource byteSource) throws ImageReadException, IOException { final List pieces = new ArrayList<>(); final List segmentPieces = new ArrayList<>(); final JpegUtils.Visitor visitor = new JpegUtils.Visitor() { // return false to exit before reading image data. @Override public boolean beginSOS() { return true; } @Override public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) { pieces.add(new JFIFPieceImageData(markerBytes, imageData)); } // return false to exit traversal. @Override public boolean visitSegment(final int marker, final byte[] markerBytes, final int segmentLength, final byte[] segmentLengthBytes, final byte[] segmentData) throws ImageReadException, IOException { final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); pieces.add(piece); segmentPieces.add(piece); return true; } }; new JpegUtils().traverseJFIF(byteSource, visitor); return new JFIFPieces(pieces, segmentPieces); } private interface SegmentFilter { boolean filter(JFIFPieceSegment segment); } protected List removeXmpSegments(final List segments) { return filterSegments(segments, XMP_SEGMENT_FILTER); } protected List removePhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER); } protected List findPhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER, true); } protected List removeExifSegments(final List segments) { return filterSegments(segments, EXIF_SEGMENT_FILTER); } protected List filterSegments(final List segments, final SegmentFilter filter) { return filterSegments(segments, filter, false); } protected List filterSegments(final List segments, final SegmentFilter filter, final boolean reverse) { final List result = new ArrayList<>(); for (final T piece : segments) { if (piece instanceof JFIFPieceSegment) { if (filter.filter((JFIFPieceSegment) piece) ^ !reverse) { result.add(piece); } } else if (!reverse) { result.add(piece); } } return result; } protected List insertBeforeFirstAppSegments( final List segments, final List newSegments) throws ImageWriteException { int firstAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { if (firstAppIndex == -1) { firstAppIndex = i; } } } final List result = new ArrayList(segments); if (firstAppIndex == -1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(firstAppIndex, newSegments); return result; } protected List insertAfterLastAppSegments( final List segments, final List newSegments) throws ImageWriteException { int lastAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { lastAppIndex = i; } } final List result = new ArrayList(segments); if (lastAppIndex == -1) { if (segments.size() < 1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(1, newSegments); } else { result.addAll(lastAppIndex + 1, newSegments); } return result; } protected void writeSegments(final OutputStream outputStream, final List segments) throws IOException { try (DataOutputStream os = new DataOutputStream(outputStream)) { JpegConstants.SOI.writeTo(os); for (final JFIFPiece piece : segments) { piece.write(os); } } } // private void writeSegment(OutputStream os, JFIFPieceSegment piece) // throws ImageWriteException, IOException // { // byte markerBytes[] = convertShortToByteArray(JPEG_APP1_MARKER, // JPEG_BYTE_ORDER); // if (piece.segmentData.length > 0xffff) // throw new JpegSegmentOverflowException("Jpeg segment is too long: " // + piece.segmentData.length); // int segmentLength = piece.segmentData.length + 2; // byte segmentLengthBytes[] = convertShortToByteArray(segmentLength, // JPEG_BYTE_ORDER); // // os.write(markerBytes); // os.write(segmentLengthBytes); // os.write(piece.segmentData); // } public static class JpegSegmentOverflowException extends ImageWriteException { private static final long serialVersionUID = -1062145751550646846L; public JpegSegmentOverflowException(final String message) { super(message); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 4290 | https://github.com/apache/commons-imaging/blob/fa7c16f434061d441d1c0d9dbcfd0f4c3092c880/src/main/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegRewriter.java/#L40-L353 | 1 | 436 | 4290 | major |
| 770 | YES I found bad smells The bad smells are: 1. Long method 2. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void fillMenuBeforeShow(final IMenuManager manager) { manager.add(openAction); manager.add(downloadToAction); manager.add(addAttachmentAction); manager.add(deleteAttachmentAction); manager.add(new Separator()); final DownloadAttachmentOpenType preferredOpenType = DownloadAttachmentOpenType.getPreferredOpenType(); if (DownloadAttachmentOpenType.BROWSER == preferredOpenType) { manager.add(openLocallyAction); } else { manager.add(openInBrowserAction); } manager.add(copyUrlToClipboardAction); } |
feature envy | Long method 2 Code duplication | t | f | f | . Long method 2. Code duplication | feature envy | 0 | 7268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/wit/FileAttachmentsControl.java/#L469-L486 | 2 | 770 | 7268 | major |
| 2886 | { "YES I found bad smells": true, "the bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 2054 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 2886 | 2054 | major |
| 1097 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Lack of encapsulation 6. Use of public fields in the builder 7. Lack of error handling and validation in the builder 8. Inconsistent formatting and spacing 9. Use of null for optional values 10. Lack of documentation and comments 11. Possible violation of single responsibility principle with the inner class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | Long method2 Feature envy 3 Code duplication 4 Inconsistent naming conventions 5 Lack of encapsulation 6 Use of public fields in the builder 7 Lack of error handling and validation in the builder 8 Inconsistent formatting and spacing 9 Use of null for optional values | t | f | f | . Long method2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Lack of encapsulation 6. Use of public fields in the builder 7. Lack of error handling and validation in the builder 8. Inconsistent formatting and spacing 9. Use of null for optional values | data class | 0 | 9800 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 2 | 1097 | 9800 | minor |
| 2129 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 13225 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 2 | 2129 | 13225 | minor | ||
| 2589 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14996 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 2 | 2589 | 14996 | critical |
| 2232 | YES, I found bad smells. The bad smells are: Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Feature envy | t | f | f | Feature envy. | data class | 0 | 13594 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 2232 | 13594 | major |
| 3750 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, PhoenixIndexFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 9355 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/write/IndexWriter.java/#L87-L100 | 1 | 3750 | 9355 | major |
| 3943 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | long method | t | t | f | long method | blob | 0 | 10322 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 1 | 3943 | 10322 | minor |
| 1821 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class TomcatInjections { // load when needed private TomcatInjections() { // no-op } private static Map> buildInjectionMap(final NamingResourcesImpl namingResources) { final Map> injectionMap = new HashMap<>(); for (final Injectable resource : namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private static void addInjectionTarget(final Injectable resource, final Map> injectionMap) { final List injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && !injectionTargets.isEmpty()) { final String jndiName = resource.getName(); for (final InjectionTarget injectionTarget : injectionTargets) { final String clazz = injectionTarget.getTargetClass(); Map injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12097 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/JavaeeInstanceManager.java/#L316-L362 | 2 | 1821 | 12097 | minor |
| 2081 | { "output": "YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 13072 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 2 | 2081 | 13072 | major |
| 2312 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14102 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 2312 | 14102 | major |
| 813 | { "message": "YES I found bad smells", "bad smells are:": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.11.0)") public class MultiGetBuildSlaveLogDirResponse implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("MultiGetBuildSlaveLogDirResponse"); private static final org.apache.thrift.protocol.TField LOG_DIRS_FIELD_DESC = new org.apache.thrift.protocol.TField("logDirs", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new MultiGetBuildSlaveLogDirResponseStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new MultiGetBuildSlaveLogDirResponseTupleSchemeFactory(); public java.util.List logDirs; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { LOG_DIRS((short)1, "logDirs"); private static final java.util.Map byName = new java.util.HashMap(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // LOG_DIRS return LOG_DIRS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.LOG_DIRS}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.LOG_DIRS, new org.apache.thrift.meta_data.FieldMetaData("logDirs", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LogDir.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(MultiGetBuildSlaveLogDirResponse.class, metaDataMap); } public MultiGetBuildSlaveLogDirResponse() { } /** * Performs a deep copy on other. */ public MultiGetBuildSlaveLogDirResponse(MultiGetBuildSlaveLogDirResponse other) { if (other.isSetLogDirs()) { java.util.List __this__logDirs = new java.util.ArrayList(other.logDirs.size()); for (LogDir other_element : other.logDirs) { __this__logDirs.add(new LogDir(other_element)); } this.logDirs = __this__logDirs; } } public MultiGetBuildSlaveLogDirResponse deepCopy() { return new MultiGetBuildSlaveLogDirResponse(this); } @Override public void clear() { this.logDirs = null; } public int getLogDirsSize() { return (this.logDirs == null) ? 0 : this.logDirs.size(); } public java.util.Iterator getLogDirsIterator() { return (this.logDirs == null) ? null : this.logDirs.iterator(); } public void addToLogDirs(LogDir elem) { if (this.logDirs == null) { this.logDirs = new java.util.ArrayList(); } this.logDirs.add(elem); } public java.util.List getLogDirs() { return this.logDirs; } public MultiGetBuildSlaveLogDirResponse setLogDirs(java.util.List logDirs) { this.logDirs = logDirs; return this; } public void unsetLogDirs() { this.logDirs = null; } /** Returns true if field logDirs is set (has been assigned a value) and false otherwise */ public boolean isSetLogDirs() { return this.logDirs != null; } public void setLogDirsIsSet(boolean value) { if (!value) { this.logDirs = null; } } public void setFieldValue(_Fields field, java.lang.Object value) { switch (field) { case LOG_DIRS: if (value == null) { unsetLogDirs(); } else { setLogDirs((java.util.List)value); } break; } } public java.lang.Object getFieldValue(_Fields field) { switch (field) { case LOG_DIRS: return getLogDirs(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case LOG_DIRS: return isSetLogDirs(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof MultiGetBuildSlaveLogDirResponse) return this.equals((MultiGetBuildSlaveLogDirResponse)that); return false; } public boolean equals(MultiGetBuildSlaveLogDirResponse that) { if (that == null) return false; if (this == that) return true; boolean this_present_logDirs = true && this.isSetLogDirs(); boolean that_present_logDirs = true && that.isSetLogDirs(); if (this_present_logDirs || that_present_logDirs) { if (!(this_present_logDirs && that_present_logDirs)) return false; if (!this.logDirs.equals(that.logDirs)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetLogDirs()) ? 131071 : 524287); if (isSetLogDirs()) hashCode = hashCode * 8191 + logDirs.hashCode(); return hashCode; } @Override public int compareTo(MultiGetBuildSlaveLogDirResponse other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetLogDirs()).compareTo(other.isSetLogDirs()); if (lastComparison != 0) { return lastComparison; } if (isSetLogDirs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.logDirs, other.logDirs); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("MultiGetBuildSlaveLogDirResponse("); boolean first = true; if (isSetLogDirs()) { sb.append("logDirs:"); if (this.logDirs == null) { sb.append("null"); } else { sb.append(this.logDirs); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class MultiGetBuildSlaveLogDirResponseStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public MultiGetBuildSlaveLogDirResponseStandardScheme getScheme() { return new MultiGetBuildSlaveLogDirResponseStandardScheme(); } } private static class MultiGetBuildSlaveLogDirResponseStandardScheme extends org.apache.thrift.scheme.StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // LOG_DIRS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list120 = iprot.readListBegin(); struct.logDirs = new java.util.ArrayList(_list120.size); LogDir _elem121; for (int _i122 = 0; _i122 < _list120.size; ++_i122) { _elem121 = new LogDir(); _elem121.read(iprot); struct.logDirs.add(_elem121); } iprot.readListEnd(); } struct.setLogDirsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.logDirs != null) { if (struct.isSetLogDirs()) { oprot.writeFieldBegin(LOG_DIRS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.logDirs.size())); for (LogDir _iter123 : struct.logDirs) { _iter123.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class MultiGetBuildSlaveLogDirResponseTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public MultiGetBuildSlaveLogDirResponseTupleScheme getScheme() { return new MultiGetBuildSlaveLogDirResponseTupleScheme(); } } private static class MultiGetBuildSlaveLogDirResponseTupleScheme extends org.apache.thrift.scheme.TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetLogDirs()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetLogDirs()) { { oprot.writeI32(struct.logDirs.size()); for (LogDir _iter124 : struct.logDirs) { _iter124.write(oprot); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list125 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.logDirs = new java.util.ArrayList(_list125.size); LogDir _elem126; for (int _i127 = 0; _i127 < _list125.size; ++_i127) { _elem126 = new LogDir(); _elem126.read(iprot); struct.logDirs.add(_elem126); } } struct.setLogDirsIsSet(true); } } } private static S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 7654 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/MultiGetBuildSlaveLogDirResponse.java/#L9-L423 | 2 | 813 | 7654 | major |
| 847 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Magic number, 4. Complex conditional logic, 5. Code duplication, 6. Inconsistent naming conventions, 7. Use of global variables, 8. Use of non-descriptive variable names, 9. Use of multiple setters/getters for single variable, 10. Violation of single responsibility principle, 11. Misuse of inheritance, 12. Lack of proper comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Long method, 2 Feature envy, 3 Magic number, 4 Complex conditional logic, 5 Code duplication, 6 Inconsistent naming conventions, 7 Use of global variables, 8 Use of non-descriptive variable names, 9 Use of multiple setters/getters for single variable, | t | f | f | . Long method, 2. Feature envy, 3. Magic number, 4. Complex conditional logic, 5. Code duplication, 6. Inconsistent naming conventions, 7. Use of global variables, 8. Use of non-descriptive variable names, 9. Use of multiple setters/getters for single variable, | data class | 0 | 7836 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 847 | 7836 | minor |
| 1525 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 11184 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 1 | 1525 | 11184 | major |
| 537 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5493 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 1 | 537 | 5493 | minor |
| 910 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
blob | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | blob | 0 | 8215 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 2 | 910 | 8215 | major |
| 905 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SequenceFileReader extends AbstractFileReader { public static final String[] defaultFields = { "key", "value" }; public static final String BUFFER_SIZE = "hdfsspout.reader.buffer.bytes"; private static final Logger LOG = LoggerFactory .getLogger(SequenceFileReader.class); private static final int DEFAULT_BUFF_SIZE = 4096; private final SequenceFile.Reader reader; private final SequenceFileReader.Offset offset; private final Key key; private final Value value; public SequenceFileReader(FileSystem fs, Path file, Map conf) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); this.offset = new SequenceFileReader.Offset(0, 0, 0); } public SequenceFileReader(FileSystem fs, Path file, Map conf, String offset) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.offset = new SequenceFileReader.Offset(offset); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); skipToOffset(this.reader, this.offset, this.key); } private static void skipToOffset(SequenceFile.Reader reader, Offset offset, K key) throws IOException { reader.sync(offset.lastSyncPoint); for (int i = 0; i < offset.recordsSinceLastSync; ++i) { reader.next(key); } } public List next() throws IOException, ParseException { if (reader.next(key, value)) { ArrayList result = new ArrayList(2); Collections.addAll(result, key, value); offset.increment(reader.syncSeen(), reader.getPosition()); return result; } return null; } @Override public void close() { try { reader.close(); } catch (IOException e) { LOG.warn("Ignoring error when closing file " + getFilePath(), e); } } public Offset getFileOffset() { return offset; } public static class Offset implements FileOffset { public long lastSyncPoint; public long recordsSinceLastSync; public long currentRecord; private long currRecordEndOffset; private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if (offset == null) { throw new IllegalArgumentException("offset cannot be null"); } if (offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if (rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord + 1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if (currentRecord < rhs.currentRecord) { return -1; } if (currentRecord == rhs.currentRecord) { return 0; } return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Offset)) { return false; } Offset offset = (Offset) o; return currentRecord == offset.currentRecord; } @Override public int hashCode() { return (int) (currentRecord ^ (currentRecord >>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if (!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 8183 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/SequenceFileReader.java/#L28-L209 | 1 | 905 | 8183 | minor |
| 682 | found NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 6594 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 2 | 682 | 6594 | minor | ||
| 3130 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 4236 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 1 | 3130 | 4236 | major |
| 1914 | YES I found bad smells The bad smells are: 1.Long method 2.Duplicated code 3.Conditional complexity 4.Inappropriate naming 5.Magic number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
feature envy | Long method2Duplicated code3Conditional complexity4Inappropriate naming5Magic number | t | f | f | .Long method2.Duplicated code3.Conditional complexity4.Inappropriate naming5.Magic number | feature envy | 0 | 12403 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 1914 | 12403 | minor |
| 769 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
blob | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy. | blob | 0 | 7259 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 769 | 7259 | minor |
| 1009 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9269 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1009 | 9269 | major |
| 226 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @HaHotStateRequired public class SensorResource extends AbstractBrooklynRestResource implements SensorApi { private static final Logger log = LoggerFactory.getLogger(SensorResource.class); @Override public List list(final String application, final String entityToken) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } List result = Lists.newArrayList(); for (AttributeSensor sensor : filter(entity.getEntityType().getSensors(), AttributeSensor.class)) { // Exclude config that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from AttributeSensor list results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } result.add(SensorTransformer.sensorSummary(entity, sensor, ui.getBaseUriBuilder())); } return result; } @Override public Map batchSensorRead(final String application, final String entityToken, final Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } Map sensorMap = Maps.newHashMap(); @SuppressWarnings("rawtypes") Iterable sensors = filter(entity.getEntityType().getSensors(), AttributeSensor.class); for (AttributeSensor sensor : sensors) { // Exclude sensors that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from current-state results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } Object value = entity.getAttribute(findSensor(entity, sensor.getName())); sensorMap.put(sensor.getName(), resolving(value).preferJson(true).asJerseyOutermostReturnValue(false).raw(raw).context(entity).timeout(Duration.ZERO).renderAs(sensor).resolve()); } return sensorMap; } protected Object get(boolean preferJson, String application, String entityToken, String sensorName, Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); AttributeSensor sensor = findSensor(entity, sensorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s' sensor '%s'", Entitlements.getEntitlementContext().user(), entity, sensor.getName()); } Object value = entity.getAttribute(sensor); return resolving(value).preferJson(preferJson).asJerseyOutermostReturnValue(true).raw(raw).context(entity).immediately(true).renderAs(sensor).resolve(); } @Override public String getPlain(String application, String entityToken, String sensorName, final Boolean raw) { return (String) get(false, application, entityToken, sensorName, raw); } @Override public Object get(final String application, final String entityToken, String sensorName, final Boolean raw) { return get(true, application, entityToken, sensorName, raw); } private AttributeSensor findSensor(Entity entity, String name) { Sensor s = entity.getEntityType().getSensor(name); if (s instanceof AttributeSensor) return (AttributeSensor) s; return new BasicAttributeSensor(Object.class, name); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void setFromMap(String application, String entityToken, Map newValues) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensors "+newValues); for (Object entry: newValues.entrySet()) { String sensorName = Strings.toString(((Map.Entry)entry).getKey()); Object newValue = ((Map.Entry)entry).getValue(); AttributeSensor sensor = findSensor(entity, sensorName); entity.sensors().set(sensor, newValue); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void set(String application, String entityToken, String sensorName, Object newValue) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensor "+sensorName+" to "+newValue); entity.sensors().set(sensor, newValue); } @Override public void delete(String application, String entityToken, String sensorName) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" deleting sensor "+sensorName); ((EntityInternal)entity).sensors().remove(sensor); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/SensorResource.java/#L46-L183 | 2 | 226 | 2447 | major |
| 2161 | { "response": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13324 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 2161 | 13324 | major |
| 5176 | { "output": "YES I found bad smells the bad smells are: Long method, Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @Metrics(context="metricssystem") public class MetricsSystemImpl extends MetricsSystem implements MetricsSource { static final Log LOG = LogFactory.getLog(MetricsSystemImpl.class); static final String MS_NAME = "MetricsSystem"; static final String MS_STATS_NAME = MS_NAME +",sub=Stats"; static final String MS_STATS_DESC = "Metrics system metrics"; static final String MS_CONTROL_NAME = MS_NAME +",sub=Control"; static final String MS_INIT_MODE_KEY = "hadoop.metrics.init.mode"; enum InitMode { NORMAL, STANDBY } private final Map sources; private final Map allSources; private final Map sinks; private final Map allSinks; private final List callbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private int period; // seconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.info(this.prefix +" metrics system started (again)"); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.info(prefix +" metrics system started in standby mode"); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.info(prefix +" metrics system started"); for (Callback cb : callbacks) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.info(prefix +" metrics system stopped (again)"); return; } for (Callback cb : callbacks) cb.preStop(); LOG.info("Stopping "+ prefix +" metrics system..."); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.info(prefix +" metrics system stopped."); for (Callback cb : callbacks) cb.postStop(); } @Override public synchronized T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { LOG.warn("Sink "+ name +" already exists!"); return sink; } allSinks.put(name, sink); if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); sa.start(); LOG.info("Registered sink "+ name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance( callback.getClass().getClassLoader(), new Class[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback "+ method.getName(), e); } return null; } })); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.save(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period * 1000; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn(e); } } }, millis, millis); LOG.info("Scheduled snapshot period at "+ period +" second(s)."); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.now(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.now() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.now(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.now() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); int confPeriod = 0; for (Entry entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); confPeriod = confPeriod == 0 ? sinkPeriod : ArithmeticUtils.gcd(confPeriod, sinkPeriod); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } period = confPeriod > 0 ? confPeriod : config.getInt(PERIOD_KEY, PERIOD_DEFAULT); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT), conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.info(prefix +" metrics system shutdown complete."); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf((m2 == null ? InitMode.NORMAL.name() : m2) .toUpperCase(Locale.US)); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14479 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java/#L69-L601 | 2 | 5176 | 14479 | major |
| 2080 | YES, I found bad smells. The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13068 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 2080 | 13068 | major |
| 2136 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class ProxiedNiFiClient implements NiFiClient { private final String proxiedEntity; private final NiFiClient wrappedClient; public ProxiedNiFiClient(final NiFiClient wrappedClient, final String proxiedEntity) { this.proxiedEntity = proxiedEntity; this.wrappedClient = wrappedClient; } @Override public ControllerClient getControllerClient() { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForToken(String token) { return wrappedClient.getControllerClientForToken(token); } @Override public FlowClient getFlowClient() { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForToken(String token) { return wrappedClient.getFlowClientForToken(token); } @Override public ProcessGroupClient getProcessGroupClient() { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForToken(String token) { return wrappedClient.getProcessGroupClientForToken(token); } @Override public VersionsClient getVersionsClient() { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForToken(String token) { return wrappedClient.getVersionsClientForToken(token); } @Override public void close() throws IOException { wrappedClient.close(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13253 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiClientFactory.java/#L113-L187 | 1 | 2136 | 13253 | minor |
| 1699 | { "message": "YES I found bad smells", "the bad smells are:": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11734 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 1699 | 11734 | minor |
| 4204 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 4204 | 11063 | minor |
| 2292 | YES I found bad smells the bad smells are: 1. Long class 2. Long method 3. Duplicate code 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NsTestPrintStream extends PrintStream { /////////////////////////////////////////////////////////////////////////////////// // // CONSTANTS // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // STATE // /////////////////////////////////////////////////////////////////////////////////// private boolean _chatty; /////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR // /////////////////////////////////////////////////////////////////////////////////// /** Construct a quiet or chatty print stream */ public NsTestPrintStream( PrintStream wrappedStream, boolean chatty ) { super( wrappedStream ); _chatty = chatty; } /////////////////////////////////////////////////////////////////////////////////// // // OVERRIDDEN BEHAVIOR // /////////////////////////////////////////////////////////////////////////////////// public PrintStream append( char c ) { if ( _chatty ) { super.append( c ); } return this; } public PrintStream append( CharSequence csq ) { if ( _chatty ) { super.append( csq ); } return this; } public PrintStream append( CharSequence csq, int start, int end ) { if ( _chatty ) { super.append( csq, start, end ); } return this; } public boolean checkError() { return super.checkError(); } protected void clearError() { super.clearError(); } public void close() { super.close(); } public void flush() { super.flush(); } public void print( boolean b ) { if ( _chatty ) { super.print( b ); } } public void print( char c ) { if ( _chatty ) { super.print( c ); } } public void print( int i ) { if ( _chatty ) { super.print( i ); } } public void print( long l ) { if ( _chatty ) { super.print( l ); } } public void print( float f ) { if ( _chatty ) { super.print( f ); } } public void print( double d ) { if ( _chatty ) { super.print( d ); } } public void print( char[] s ) { if ( _chatty ) { super.print( s ); } } public void print( String s ) { if ( _chatty ) { super.print( s ); } } public void print( Object obj ) { if ( _chatty ) { super.print( obj ); } } public void println() { if ( _chatty ) { super.println(); } } public void println( boolean x ) { if ( _chatty ) { super.println( x ); } } public void println( char x ) { if ( _chatty ) { super.println( x ); } } public void println( int x ) { if ( _chatty ) { super.println( x ); } } public void println( long x ) { if ( _chatty ) { super.println( x ); } } public void println( float x ) { if ( _chatty ) { super.println( x ); } } public void println( double x ) { if ( _chatty ) { super.println( x ); } } public void println( char[] x ) { if ( _chatty ) { super.println( x ); } } public void println( String x ) { if ( _chatty ) { super.println( x ); } } public void println( Object x ) { if ( _chatty ) { super.println( x ); } } public PrintStream printf( String format, Object... args ) { if ( _chatty ) { super.printf( format, args ); } return this; } public PrintStream printf( Locale l, String format, Object... args ) { if ( _chatty ) { super.printf( l, format, args ); } return this; } public PrintStream format( String format, Object... args ) { if ( _chatty ) { super.format( format, args ); } return this; } public PrintStream format( Locale l, String format, Object... args ) { if ( _chatty ) { super.format( l, format, args ); } return this; } public void write( byte[] buf, int off, int len ) { if ( _chatty ) { super.write( buf, off, len ); } } public void write( int b ) { if ( _chatty ) { super.write( b ); } } } |
blob | Long class2 Long method3 Duplicate code4 Feature envy | t | f | f | . Long class2. Long method3. Duplicate code4. Feature envy | blob | 0 | 13949 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.tests/org/apache/derbyTesting/system/nstest/NsTestPrintStream.java/#L31-L127 | 2 | 2292 | 13949 | minor |
| 321 | YES I found bad smells the bad smells are: 1.Duplicate code 2.Magic numbers 3.Trainwreck 4.Long class 5.Leaking this in constructor | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | Duplicate code2Magic numbers3Trainwreck4Long class5Leaking this in constructor | t | f | f | .Duplicate code2.Magic numbers3.Trainwreck4.Long class5.Leaking this in constructor | blob | 0 | 3298 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 2 | 321 | 3298 | major |
| 944 | YES I found bad smells the bad smells are: 1. Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain. 2. Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation. 3. Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle. 4. Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values. 5. Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle. 6. Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code. 7. Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code. 8. Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand. 9. Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain2 Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation3 Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle4 Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values5 Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle6 Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code7 Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code8 Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand9 Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability | t | f | f | . Long Constructors: The constructors are quite long with many parameters, which could potentially make the code difficult to understand and maintain.2. Feature Envy: Some of the methods seem to be overly accessing or manipulating data from other classes, indicating potential poor design or violation of encapsulation.3. Large Class: The SimpleMessage class may be doing too many things and violating the Single Responsibility Principle.4. Primitive Obsession: The class is relying on primitive data types (strings, ints, longs) instead of creating custom objects to represent those values.5. Shotgun Surgery: Making changes to the class may require changes to multiple methods, indicating a potential violation of the Open/Closed Principle.6. Lack of proper code organization: The methods within the class do not seem to have a clear organizational structure, making it difficult to understand the flow of the code.7. Unnecessary comments: Some of the comments within the code may be unnecessary and not adding any value to the understanding of the code.8. Inconsistent formatting: The code follows inconsistent formatting, making it difficult to read and understand.9. Unnecessary duplication: The code contains some duplication, which could be refactored to improve maintainability and readability. | data class | 0 | 8474 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 944 | 8474 | major |
| 2270 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13763 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 2270 | 13763 | minor |
| 1012 | { "message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void write(DataOutputView out) throws IOException { out.writeInt(position); for (int i = 0; i < position; i++) { out.writeDouble(data[i]); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9274 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/DoubleValueArray.java/#L179-L186 | 1 | 1012 | 9274 | major |
| 2427 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 14446 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 2427 | 14446 | minor |
| 2468 | <br> YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 14570 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 2 | 2468 | 14570 | minor |
| 10 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
feature envy | Not specified | f | f | f | false | 0 | 613 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 2 | 10 | 613 | minor | |
| 3909 | YES, I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10235 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 2 | 3909 | 10235 | minor |
| 277 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Complex conditional logic 5. Inefficient use of buffers 6. Unnecessary use of exceptions 7. Poor exception handling 8. Code duplication in the catch block 9. Feature envy between the FlowFilePackagerV1 and FlowFileUnpackagerV1 classes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } } |
blob | Long method2 Feature envy3 Duplicated code4 Complex conditional logic5 Inefficient use of buffers6 Unnecessary use of exceptions7 Poor exception handling8 Code duplication in the catch block9 Feature envy between the FlowFilePackagerV | t | f | f | . Long method2. Feature envy3. Duplicated code4. Complex conditional logic5. Inefficient use of buffers6. Unnecessary use of exceptions7. Poor exception handling8. Code duplication in the catch block9. Feature envy between the FlowFilePackagerV | blob | 0 | 2971 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 | 2 | 277 | 2971 | minor |
| 777 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
blob | data class | t | t | f | data class | blob | 0 | 7370 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 1 | 777 | 7370 | minor |
| 453 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicated code 4. Magic numbers 5. Excessive comments/unused comments 6. Inconsistent naming conventions 7. Dead code 8. Unnecessary synchronization 9. Unnecessary locking 10. Complex constructor 11. Duplicate code in constructors 12. Excessive use of boolean flags 13. Nested class with complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class DocumentsWriterDeleteQueue implements Accountable { // the current end (latest delete operation) in the delete queue: private volatile Node tail; /** Used to record deletes against all prior (already written to disk) segments. Whenever any segment flushes, we bundle up this set of * deletes and insert into the buffered updates stream before the newly flushed segment(s). */ private final DeleteSlice globalSlice; private final BufferedUpdates globalBufferedUpdates; // only acquired to update the global deletes, pkg-private for access by tests: final ReentrantLock globalBufferLock = new ReentrantLock(); final long generation; /** Generates the sequence number that IW returns to callers changing the index, showing the effective serialization of all operations. */ private final AtomicLong nextSeqNo; private final InfoStream infoStream; // for asserts long maxSeqNo = Long.MAX_VALUE; DocumentsWriterDeleteQueue(InfoStream infoStream) { // seqNo must start at 1 because some APIs negate this to also return a boolean this(infoStream, 0, 1); } DocumentsWriterDeleteQueue(InfoStream infoStream, long generation, long startSeqNo) { this(infoStream, new BufferedUpdates("global"), generation, startSeqNo); } DocumentsWriterDeleteQueue(InfoStream infoStream, BufferedUpdates globalBufferedUpdates, long generation, long startSeqNo) { this.infoStream = infoStream; this.globalBufferedUpdates = globalBufferedUpdates; this.generation = generation; this.nextSeqNo = new AtomicLong(startSeqNo); /* * we use a sentinel instance as our initial tail. No slice will ever try to * apply this tail since the head is always omitted. */ tail = new Node<>(null); // sentinel globalSlice = new DeleteSlice(tail); } long addDelete(Query... queries) { long seqNo = add(new QueryArrayNode(queries)); tryApplyGlobalSlice(); return seqNo; } long addDelete(Term... terms) { long seqNo = add(new TermArrayNode(terms)); tryApplyGlobalSlice(); return seqNo; } long addDocValuesUpdates(DocValuesUpdate... updates) { long seqNo = add(new DocValuesUpdatesNode(updates)); tryApplyGlobalSlice(); return seqNo; } static Node newNode(Term term) { return new TermNode(term); } static Node newNode(DocValuesUpdate... updates) { return new DocValuesUpdatesNode(updates); } /** * invariant for document update */ long add(Node deleteNode, DeleteSlice slice) { long seqNo = add(deleteNode); /* * this is an update request where the term is the updated documents * delTerm. in that case we need to guarantee that this insert is atomic * with regards to the given delete slice. This means if two threads try to * update the same document with in turn the same delTerm one of them must * win. By taking the node we have created for our del term as the new tail * it is guaranteed that if another thread adds the same right after us we * will apply this delete next time we update our slice and one of the two * competing updates wins! */ slice.sliceTail = deleteNode; assert slice.sliceHead != slice.sliceTail : "slice head and tail must differ after add"; tryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe // we can do it just every n times or so? return seqNo; } synchronized long add(Node newNode) { tail.next = newNode; this.tail = newNode; return getNextSequenceNumber(); } boolean anyChanges() { globalBufferLock.lock(); try { /* * check if all items in the global slice were applied * and if the global slice is up-to-date * and if globalBufferedUpdates has changes */ return globalBufferedUpdates.any() || !globalSlice.isEmpty() || globalSlice.sliceTail != tail || tail.next != null; } finally { globalBufferLock.unlock(); } } void tryApplyGlobalSlice() { if (globalBufferLock.tryLock()) { /* * The global buffer must be locked but we don't need to update them if * there is an update going on right now. It is sufficient to apply the * deletes that have been added after the current in-flight global slices * tail the next time we can get the lock! */ try { if (updateSliceNoSeqNo(globalSlice)) { globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } } finally { globalBufferLock.unlock(); } } } FrozenBufferedUpdates freezeGlobalBuffer(DeleteSlice callerSlice) throws IOException { globalBufferLock.lock(); /* * Here we freeze the global buffer so we need to lock it, apply all * deletes in the queue and reset the global slice to let the GC prune the * queue. */ final Node currentTail = tail; // take the current tail make this local any // Changes after this call are applied later // and not relevant here if (callerSlice != null) { // Update the callers slices so we are on the same page callerSlice.sliceTail = currentTail; } try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } if (globalBufferedUpdates.any()) { final FrozenBufferedUpdates packet = new FrozenBufferedUpdates(infoStream, globalBufferedUpdates, null); globalBufferedUpdates.clear(); return packet; } else { return null; } } finally { globalBufferLock.unlock(); } } DeleteSlice newSlice() { return new DeleteSlice(tail); } /** Negative result means there were new deletes since we last applied */ synchronized long updateSlice(DeleteSlice slice) { long seqNo = getNextSequenceNumber(); if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; seqNo = -seqNo; } return seqNo; } /** Just like updateSlice, but does not assign a sequence number */ boolean updateSliceNoSeqNo(DeleteSlice slice) { if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; return true; } return false; } static class DeleteSlice { // No need to be volatile, slices are thread captive (only accessed by one thread)! Node sliceHead; // we don't apply this one Node sliceTail; DeleteSlice(Node currentTail) { assert currentTail != null; /* * Initially this is a 0 length slice pointing to the 'current' tail of * the queue. Once we update the slice we only need to assign the tail and * have a new slice */ sliceHead = sliceTail = currentTail; } void apply(BufferedUpdates del, int docIDUpto) { if (sliceHead == sliceTail) { // 0 length slice return; } /* * When we apply a slice we take the head and get its next as our first * item to apply and continue until we applied the tail. If the head and * tail in this slice are not equal then there will be at least one more * non-null node in the slice! */ Node current = sliceHead; do { current = current.next; assert current != null : "slice property violated between the head on the tail must not be a null node"; current.apply(del, docIDUpto); } while (current != sliceTail); reset(); } void reset() { // Reset to a 0 length slice sliceHead = sliceTail; } /** * Returns true iff the given node is identical to the the slices tail, * otherwise false. */ boolean isTail(Node node) { return sliceTail == node; } /** * Returns true iff the given item is identical to the item * hold by the slices tail, otherwise false. */ boolean isTailItem(Object object) { return sliceTail.item == object; } boolean isEmpty() { return sliceHead == sliceTail; } } public int numGlobalTermDeletes() { return globalBufferedUpdates.numTermDeletes.get(); } void clear() { globalBufferLock.lock(); try { final Node currentTail = tail; globalSlice.sliceHead = globalSlice.sliceTail = currentTail; globalBufferedUpdates.clear(); } finally { globalBufferLock.unlock(); } } static class Node { volatile Node next; final T item; Node(T item) { this.item = item; } void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { throw new IllegalStateException("sentinel item must never be applied"); } boolean isDelete() { return true; } } private static final class TermNode extends Node { TermNode(Term term) { super(term); } @Override void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { bufferedDeletes.addTerm(item, docIDUpto); } @Override public String toString() { return "del=" + item; } } private static final class QueryArrayNode extends Node { QueryArrayNode(Query[] query) { super(query); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Query query : item) { bufferedUpdates.addQuery(query, docIDUpto); } } } private static final class TermArrayNode extends Node { TermArrayNode(Term[] term) { super(term); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Term term : item) { bufferedUpdates.addTerm(term, docIDUpto); } } @Override public String toString() { return "dels=" + Arrays.toString(item); } } private static final class DocValuesUpdatesNode extends Node { DocValuesUpdatesNode(DocValuesUpdate... updates) { super(updates); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (DocValuesUpdate update : item) { switch (update.type) { case NUMERIC: bufferedUpdates.addNumericUpdate((NumericDocValuesUpdate) update, docIDUpto); break; case BINARY: bufferedUpdates.addBinaryUpdate((BinaryDocValuesUpdate) update, docIDUpto); break; default: throw new IllegalArgumentException(update.type + " DocValues updates not supported yet!"); } } } @Override boolean isDelete() { return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("docValuesUpdates: "); if (item.length > 0) { sb.append("term=").append(item[0].term).append("; updates: ["); for (DocValuesUpdate update : item) { sb.append(update.field).append(':').append(update.valueToString()).append(','); } sb.setCharAt(sb.length()-1, ']'); } return sb.toString(); } } private boolean forceApplyGlobalSlice() { globalBufferLock.lock(); final Node currentTail = tail; try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } return globalBufferedUpdates.any(); } finally { globalBufferLock.unlock(); } } public int getBufferedUpdatesTermsSize() { globalBufferLock.lock(); try { forceApplyGlobalSlice(); return globalBufferedUpdates.deleteTerms.size(); } finally { globalBufferLock.unlock(); } } @Override public long ramBytesUsed() { return globalBufferedUpdates.ramBytesUsed(); } @Override public String toString() { return "DWDQ: [ generation: " + generation + " ]"; } public long getNextSequenceNumber() { long seqNo = nextSeqNo.getAndIncrement(); assert seqNo < maxSeqNo: "seqNo=" + seqNo + " vs maxSeqNo=" + maxSeqNo; return seqNo; } public long getLastSequenceNumber() { return nextSeqNo.get()-1; } /** Inserts a gap in the sequence numbers. This is used by IW during flush or commit to ensure any in-flight threads get sequence numbers * inside the gap */ public void skipSequenceNumbers(long jump) { nextSeqNo.addAndGet(jump); } } |
blob | Feature envy2 Long method3 Duplicated code4 Magic numbers5 Excessive comments/unused comments6 Inconsistent naming conventions7 Dead code8 Unnecessary synchronization9 Unnecessary locking | t | f | f | . Feature envy2. Long method3. Duplicated code4. Magic numbers5. Excessive comments/unused comments6. Inconsistent naming conventions7. Dead code8. Unnecessary synchronization9. Unnecessary locking | blob | 0 | 4437 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java/#L71-L495 | 2 | 453 | 4437 | major |
| 778 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static final class TomcatInjections { // load when needed private TomcatInjections() { // no-op } private static Map> buildInjectionMap(final NamingResourcesImpl namingResources) { final Map> injectionMap = new HashMap<>(); for (final Injectable resource : namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private static void addInjectionTarget(final Injectable resource, final Map> injectionMap) { final List injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && !injectionTargets.isEmpty()) { final String jndiName = resource.getName(); for (final InjectionTarget injectionTarget : injectionTargets) { final String clazz = injectionTarget.getTargetClass(); Map injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } } |
blob | long method | t | t | f | long method | blob | 0 | 7445 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/JavaeeInstanceManager.java/#L316-L362 | 1 | 778 | 7445 | minor |
| 2350 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14205 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 1 | 2350 | 14205 | minor |
| 936 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 8410 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 936 | 8410 | major |
| 1684 | YES I found bad smells. The bad smells are: Long method, Feature envy, Duplicate code, Long parameter list. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
blob | Long method, Feature envy, Duplicate code, Long parameter list | t | f | f | Long method, Feature envy, Duplicate code, Long parameter list. | blob | 0 | 11684 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 2 | 1684 | 11684 | minor |
| 800 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | long method | t | t | f | long method | data class | 0 | 7573 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 1 | 800 | 7573 | minor |
| 645 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6363 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 | 2 | 645 | 6363 | critical |
| 1649 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } } |
blob | data class | t | t | f | data class | blob | 0 | 11566 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 | 1 | 1649 | 11566 | critical |
| 1856 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
blob | Long method2 Feature envy3 Data class4 Primitive obsession | t | f | f | . Long method2. Feature envy3. Data class4. Primitive obsession | blob | 0 | 12215 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 1856 | 12215 | minor |
| 616 | {"response":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | long method | t | t | f | long method | blob | 0 | 6180 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 1 | 616 | 6180 | minor |
| 286 | {"message": "YES I found bad smells", "bad smells are": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 3056 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 2 | 286 | 3056 | major |
| 2044 | {"message":"YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 12869 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 2044 | 12869 | minor |
| 5249 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14679 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 2 | 5249 | 14679 | minor | ||
| 1395 | { "message": "YES I found bad smells", "smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10851 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1395 | 10851 | minor |
| 660 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 6430 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 660 | 6430 | major |
| 404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions - the class name is "BoltExecutorStats" while other variables and methods use plural naming conventions. 4. Magic numbers - the constructor and other methods use unspecified numbers as parameters. 5. Lack of comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | Long method2 Feature envy3 Inconsistent naming conventions - the class name is "BoltExecutorStats" while other variables and methods use plural naming conventions4 Magic numbers - the constructor and other methods use unspecified numbers as parameters5 Lack of comments/documentation | t | f | f | . Long method2. Feature envy3. Inconsistent naming conventions - the class name is "BoltExecutorStats" while other variables and methods use plural naming conventions.4. Magic numbers - the constructor and other methods use unspecified numbers as parameters.5. Lack of comments/documentation. | blob | 0 | 4119 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 404 | 4119 | minor |
| 718 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class GenericConnectionStatusHtmlCreator { public static String generateConnectionViewHtml(String providerDisplayName, String providerId, UserProfile profile) { String escProviderDisplayName = escape(providerDisplayName); StringBuilder builder = new StringBuilder(); if (profile == null) { builder.append("Connect to " + escProviderDisplayName + ""); builder.append(""); builder.append(""); builder.append("You aren't connected to "); builder.append(escProviderDisplayName); builder.append(" yet. Click the button to connect with your "); builder.append(escProviderDisplayName); builder.append(" account."); builder.append(""); builder.append("Connect to "); builder.append(escProviderDisplayName); builder.append(""); builder.append(""); } else { String escProfileName = escape(profile.getName()); builder.append("Connected to "); builder.append(escProviderDisplayName); builder.append(""); builder.append("Hello, "); builder.append(escProfileName); builder.append("!You are now connected to "); builder.append(escProviderDisplayName); String username = profile.getUsername(); if (username !=null) { builder.append(" as "); builder.append(escape(username)); } builder.append("."); } return builder.toString(); } private static String escape(String in) { return htmlEscape(in).replaceAll("\\{", "{").replaceAll("\\}", "}"); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6828 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-web/src/main/java/org/springframework/social/connect/web/GenericConnectionStatusView.java/#L91-L138 | 2 | 718 | 6828 | minor |
| 4680 | {"response": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuckAddDependencyIntention extends BaseIntentionAction { private static Logger LOGGER = Logger.getInstance(BuckAddDependencyIntention.class); /** * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the * given reference element to those of the given psiClass. * * Note that this intention can fail to be created if either side of the edge cannot be * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking * this intention may fail to create edges in either the Buck target graph or the IntelliJ module * graph (or both). */ @Nullable public static BuckAddDependencyIntention create( PsiJavaCodeReferenceElement referenceElement, PsiClass psiClass) { VirtualFile editSourceFile = referenceElement.getContainingFile().getVirtualFile(); if (editSourceFile == null) { return null; } Project project = referenceElement.getProject(); BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); VirtualFile editBuildFile = buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null); if (editBuildFile == null) { return null; } VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile(); if (importSourceFile == null) { return null; } VirtualFile importBuildFile = buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null); if (importBuildFile == null) { return null; } if (importBuildFile.equals(editBuildFile)) { return null; } ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); Module editModule = projectFileIndex.getModuleForFile(editSourceFile); if (editModule == null) { return null; } Module importModule = projectFileIndex.getModuleForFile(importSourceFile); if (importModule == null) { return null; } BuckTarget editSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(editSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (editSourceTarget == null) { return null; } BuckTarget importSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(importSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (importSourceTarget == null) { return null; } return new BuckAddDependencyIntention( project, referenceElement, editBuildFile, editSourceFile, editSourceTarget, editModule, psiClass, importBuildFile, importSourceFile, importSourceTarget, importModule); } private Project project; // Fields pertaining to the element in the file being edited private PsiJavaCodeReferenceElement referenceElement; private VirtualFile editBuildFile; private VirtualFile editSourceFile; private BuckTarget editSourceTarget; private BuckTarget editTarget; private Module editModule; // Fields pertaining to the dependency that should be resolved/imported private PsiClass psiClass; private VirtualFile importBuildFile; private VirtualFile importSourceFile; private BuckTarget importSourceTarget; private BuckTarget importTarget; private Module importModule; BuckAddDependencyIntention( Project project, PsiJavaCodeReferenceElement referenceElement, VirtualFile editBuildFile, VirtualFile editSourceFile, BuckTarget editSourceTarget, Module editModule, PsiClass psiClass, VirtualFile importBuildFile, VirtualFile importSourceFile, BuckTarget importSourceTarget, Module importModule) { this.project = project; this.referenceElement = referenceElement; this.editBuildFile = editBuildFile; this.editSourceFile = editSourceFile; this.editSourceTarget = editSourceTarget; this.editModule = editModule; this.psiClass = psiClass; this.importBuildFile = importBuildFile; this.importSourceFile = importSourceFile; this.importSourceTarget = importSourceTarget; this.importModule = importModule; String message = "Add BUCK dependency on owner(" + importSourceTarget + ")"; setText(message); } @Nls(capitalization = Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return this.getClass().getSimpleName(); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { String msg = "Invoked for project " + project.getName() + " and file " + psiFile.getName(); LOGGER.info(msg); queryBuckForTargets(editor); } /** Helper class to handle deserialization of buck query. */ static class TargetMetadata { public BuckTarget target; public @Nullable List deps; public @Nullable List visibility; // null means PUBLIC public @Nullable List srcs; public @Nullable List resources; static TargetMetadata from( BuckTargetLocator buckTargetLocator, BuckTarget target, JsonObject payload) { TargetMetadata targetMetadata = new TargetMetadata(); targetMetadata.target = target; targetMetadata.srcs = stringListOrNull(payload.get("srcs")); targetMetadata.resources = stringListOrNull(payload.get("resources")); // Deps are a list of BuckTargets targetMetadata.deps = Optional.ofNullable(stringListOrNull(payload.get("deps"))) .map( deps -> deps.stream() .map( s -> BuckTarget.parse(s).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList())) .orElse(null); // Visibilility falls in one of three cases: // (1) if unspecified => means visibility is limited to the current package // (2) contains "PUBLIC" => available everywhere // (3) otherwise is a list of buck target patterns where it is visible List optionalVisibility = stringListOrNull(payload.get("visibility")); if (optionalVisibility == null) { targetMetadata.visibility = Collections.singletonList(target.asPattern().asPackageMatchingPattern()); } else if (optionalVisibility.contains("PUBLIC")) { targetMetadata.visibility = null; // } else { targetMetadata.visibility = optionalVisibility .stream() .map(p -> BuckTargetPattern.parse(p).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList()); } return targetMetadata; } static @Nullable List stringListOrNull(@Nullable JsonElement jsonElement) { if (jsonElement == null) { return null; } return new Gson().fromJson(jsonElement, new TypeToken>() {}.getType()); } boolean isVisibleTo(BuckTarget target) { if (visibility == null) { return true; } return visibility.stream().anyMatch(pattern -> pattern.matches(target)); } boolean hasDependencyOn(BuckTarget target) { return deps.stream().anyMatch(dep -> dep.equals(target)); } boolean contains(BuckTarget targetFile) { if (!target.asPattern().asPackageMatchingPattern().matches(targetFile)) { return false; } String relativeToBuildFile = targetFile.getRuleName(); return srcs.contains(relativeToBuildFile) || resources.contains(relativeToBuildFile); } } /** Queries buck for targets that own the editSourceFile and the importSourceFile. */ private void queryBuckForTargets(Editor editor) { BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); String editPath = editSourceFile.getPath(); String importPath = importSourceFile.getPath(); BuckJsonCommandHandler> handler = new BuckJsonCommandHandler<>( project, BuckCommand.QUERY, new Callback>() { @Override public List deserialize(JsonElement jsonElement) throws IOException { Type type = new TypeToken>() {}.getType(); Map raw = new Gson().fromJson(jsonElement, type); List results = new ArrayList<>(); for (Entry entry : raw.entrySet()) { BuckTarget.parse(entry.getKey()) .map(buckTargetLocator::resolve) .map( target -> TargetMetadata.from(buckTargetLocator, target, entry.getValue())) .ifPresent(results::add); } return results; } @Override public void onSuccess(List results, String stderr) { List editTargets = new ArrayList<>(); List importTargets = new ArrayList<>(); for (TargetMetadata targetMetadata : results) { if (targetMetadata.contains(editSourceTarget)) { editTargets.add(targetMetadata); } if (targetMetadata.contains(importSourceTarget)) { importTargets.add(targetMetadata); } } updateDependencies(editor, editTargets, importTargets); } @Override public void onFailure( String stdout, String stderr, @Nullable Integer exitCode, @Nullable Throwable throwable) { BuckNotification.getInstance(project) .showWarningBalloon( "Could not determine owners for " + editSourceFile + " and/or " + importSourceFile); return; } }); handler .command() .addParameters( "owner(%s)", editPath, importPath, "--output-attributes=deps|srcs|visibility|resources"); handler.runInCurrentThreadPostEnd(() -> {}); } /** * Implementation of {@link * com.intellij.notification.NotificationListener#hyperlinkUpdate(Notification, HyperlinkEvent)}. */ private void hyperlinkActivated( @NotNull Notification notification, @NotNull HyperlinkEvent event) { String href = event.getDescription(); switch (href) { case "editTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(editTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "editBuildFile": FileEditorManager.getInstance(project).openFile(editBuildFile, true); break; case "editSourceFile": FileEditorManager.getInstance(project).openFile(editSourceFile, true); break; case "importTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(importTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "importBuildFile": FileEditorManager.getInstance(project).openFile(importBuildFile, true); break; case "importSourceFile": FileEditorManager.getInstance(project).openFile(importSourceFile, true); break; } } private void updateDependencies( Editor editor, List editTargets, List importTargets) { if (editTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + editSourceTarget + " in " + editBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (importTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + importSourceTarget + " in " + importBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } TargetMetadata editTargetMetadata = editTargets.get(0); TargetMetadata importTargetMetadata = importTargets.get(0); editTarget = editTargetMetadata.target; importTarget = importTargetMetadata.target; if (!importTargetMetadata.isVisibleTo(editTarget)) { String message = "Add dependency failed: The target " + importTarget + " is not visible to " + editTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (!editTargetMetadata.hasDependencyOn(importTarget)) { if (!BuckDeps.modifyTargetToAddDependency( editBuildFile, editTarget.toString(), importTarget.toString())) { String message = "Add dependency failed: Could not add modify build file for " + editTarget + " to add dependency on " + importTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } } else { String message = "No need to modify build file " + editBuildFile + ", already has dependency from " + editTarget + " to " + importTarget + ""; BuckNotification.getInstance(project).showInfoBalloon(message, this::hyperlinkActivated); } ModuleRootModificationUtil.updateModel( editModule, (modifiableRootModel -> { if (modifiableRootModel.findModuleOrderEntry(importModule) != null) { LOGGER.info( "No need to modify module " + editModule.getName() + ", already has dependency on " + importModule.getName()); } else { modifiableRootModel.addModuleOrderEntry(importModule); LOGGER.info( "Successfully added module dependency from " + editModule.getName() + " on " + importModule.getName()); } new AddImportAction(project, referenceElement, editor, psiClass).execute(); })); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12526 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/autodeps/BuckAddDependencyIntention.java/#L66-L480 | 2 | 4680 | 12526 | critical |
| 5526 | YES I found bad smells the bad smells are: 1. Blob 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void asJson(OutputStream out, Map data) throws HiveException { try { new ObjectMapper().writeValue(out, data); } catch (IOException e) { throw new HiveException("Unable to convert to json", e); } } |
feature envy | Blob2 Long method | t | f | f | . Blob2. Long method | feature envy | 0 | 5595 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/JsonMetaDataFormatter.java/#L76-L84 | 1 | 5526 | 5595 | minor |
| 2171 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13382 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 2 | 2171 | 13382 | major |
| 1529 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11204 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 2 | 1529 | 11204 | major |
| 952 | { "answer": "YES I found bad smells", "bad smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ConfigurationInfo(CompositeData cd) { this.settings = createMap(cd.get("settings")); this.name = (String) cd.get("name"); this.label = (String) cd.get("label"); this.description = (String) cd.get("description"); this.provider = (String) cd.get("provider"); this.contents = (String) cd.get("contents"); } |
feature envy | blob | t | t | f | blob | feature envy | 0 | 8527 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.management.jfr/share/classes/jdk/management/jfr/ConfigurationInfo.java/#L63-L70 | 1 | 952 | 8527 | major |
| 1472 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
data class | Long method, 2Feature envy: | t | f | f | .Long method, 2.Feature envy: | data class | 0 | 11052 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 2 | 1472 | 11052 | minor |
| 661 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6434 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 1 | 661 | 6434 | critical |
| 2515 | YES, I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14695 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 2 | 2515 | 14695 | major |
| 2146 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13275 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 2146 | 13275 | major |
| 283 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private final class SymbolProcessor implements FunctionVisitor, InstructionVisitorAdapter { private final SourceFunction function; private final LinkedList removeFromBlock = new LinkedList<>(); private int blockInstIndex = 0; private DbgValueInstruction lastDbgValue = null; private InstructionBlock currentBlock = null; private SymbolProcessor(SourceFunction function) { this.function = function; } @Override public void visit(InstructionBlock block) { currentBlock = block; lastDbgValue = null; for (blockInstIndex = 0; blockInstIndex < block.getInstructionCount(); blockInstIndex++) { block.getInstruction(blockInstIndex).accept(this); } if (!removeFromBlock.isEmpty()) { for (int i : removeFromBlock) { currentBlock.remove(i); } removeFromBlock.clear(); } } @Override public void visitInstruction(Instruction instruction) { final MDLocation loc = instruction.getDebugLocation(); if (loc != null) { final LLVMSourceLocation scope = cache.buildLocation(loc); if (scope != null) { instruction.setSourceLocation(scope); } } } @Override public void visit(VoidCallInstruction call) { final SymbolImpl callTarget = call.getCallTarget(); if (callTarget instanceof FunctionDeclaration) { switch (((FunctionDeclaration) callTarget).getName()) { case LLVM_DBG_DECLARE_NAME: handleDebugIntrinsic(call, true); return; case LLVM_DBG_ADDR_NAME: // dbg.declare and dbg.addr have the same interface and, for our purposes, // the same semantics handleDebugIntrinsic(call, true); return; case LLVM_DBG_VALUE_NAME: handleDebugIntrinsic(call, false); return; case LLVM_DEBUGTRAP_NAME: visitDebugTrap(call); return; } } visitInstruction(call); } private void visitDebugTrap(VoidCallInstruction call) { final DebugTrapInstruction trap = DebugTrapInstruction.create(call); currentBlock.set(blockInstIndex, trap); visitInstruction(trap); } private SourceVariable getVariable(VoidCallInstruction call, int index) { final SymbolImpl varSymbol = getArg(call, index); if (varSymbol instanceof MetadataSymbol) { final MDBaseNode mdLocal = ((MetadataSymbol) varSymbol).getNode(); final LLVMSourceSymbol symbol = cache.getSourceSymbol(mdLocal, false); return function.getLocal(symbol); } return null; } private void handleDebugIntrinsic(VoidCallInstruction call, boolean isDeclaration) { SymbolImpl value = getArg(call, LLVM_DBG_INTRINSICS_VALUE_ARGINDEX); if (value instanceof MetadataSymbol) { value = MDSymbolExtractor.getSymbol(((MetadataSymbol) value).getNode()); } if (value == null) { // this may happen if llvm optimizations removed a variable value = new NullConstant(MetaType.DEBUG); } else if (value instanceof ValueInstruction) { ((ValueInstruction) value).setSourceVariable(true); } else if (value instanceof FunctionParameter) { ((FunctionParameter) value).setSourceVariable(true); } int mdLocalArgIndex; int mdExprArgIndex; if (isDeclaration) { mdLocalArgIndex = LLVM_DBG_DECLARE_LOCALREF_ARGINDEX; mdExprArgIndex = LLVM_DBG_DECLARE_EXPR_ARGINDEX; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_NEW) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_NEW; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_NEW; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_OLD; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_OLD; } else { return; } final SourceVariable variable = getVariable(call, mdLocalArgIndex); if (variable == null) { // invalid or unsupported debug information // remove upper indices so we do not need to update the later ones removeFromBlock.addFirst(blockInstIndex); return; } final MDExpression expression = getExpression(call, mdExprArgIndex); if (ValueFragment.describesFragment(expression)) { variable.addFragment(ValueFragment.parse(expression)); } else { variable.addFullDefinition(); } if (isDeclaration) { final DbgDeclareInstruction dbgDeclare = new DbgDeclareInstruction(value, variable, expression); variable.addDeclaration(dbgDeclare); currentBlock.set(blockInstIndex, dbgDeclare); } else { long index = 0; if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { final SymbolImpl indexSymbol = call.getArgument(LLVM_DBG_VALUE_INDEX_ARGINDEX_OLD); final Long l = LLVMSymbolReadResolver.evaluateLongIntegerConstant(indexSymbol); if (l != null) { index = l; } } final DbgValueInstruction dbgValue = new DbgValueInstruction(value, variable, index, expression); if (dbgValue.equals(lastDbgValue)) { // at higher optimization levels llvm often duplicates the @llvm.dbg.value // intrinsic call, we remove it again to avoid unnecessary runtime overhead removeFromBlock.addFirst(blockInstIndex); } else { variable.addValue(dbgValue); currentBlock.set(blockInstIndex, dbgValue); lastDbgValue = dbgValue; } } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 3035 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/sulong/projects/com.oracle.truffle.llvm.parser/src/com/oracle/truffle/llvm/parser/metadata/debuginfo/DebugInfoFunctionProcessor.java/#L145-L308 | 1 | 283 | 3035 | critical |
| 1787 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | t | f | f | long method | 0 | 11981 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 1787 | 11981 | minor | ||
| 1824 | YES I found bad smells 1. Long method 2. Feature envy 3. Duplicate code 4. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | Long method2 Feature envy3 Duplicate code 4 Code duplication | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Code duplication | blob | 0 | 12104 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 2 | 1824 | 12104 | minor |
| 395 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component("org.apache.usergrid.rest.management.organizations.applications.ApplicationResource") @Scope("prototype") @Produces({ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", "text/jscript" }) public class ApplicationResource extends AbstractContextResource { private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); public static final String CONFIRM_APPLICATION_IDENTIFIER = "confirm_application_identifier"; public static final String RESTORE_PASSWORD = "restore_password"; //@Autowired //protected ExportService exportService; OrganizationInfo organization; UUID applicationId; ApplicationInfo application; @Autowired private SignInProviderFactory signInProviderFactory; public ApplicationResource() { } public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { this.organization = organization; this.applicationId = applicationId; return this; } public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { this.organization = organization; applicationId = application.getId(); this.application = application; return this; } @RequireOrganizationAccess @GET @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getApplication( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); ServiceManager sm = smf.getServiceManager( applicationId ); response.setAction( "get" ); response.setApplication( sm.getApplication() ); response.setParams( ui.getQueryParameters() ); response.setResults( management.getApplicationMetadata( applicationId ) ); return response; } @RequireOrganizationAccess @GET @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get application client credentials"); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.getClientSecretForApplication( applicationId ) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @POST @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse generateCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "generate application client credentials" ); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.newClientSecretForApplication(applicationId) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @GET @JSONP @Path("_size") public ApiResponse getApplicationSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "get application size for all entities" ); long size = management.getApplicationSize(this.applicationId); Map map = new HashMap<>(); Map innerMap = new HashMap<>(); Map sumMap = new HashMap<>(); innerMap.put("application",size); sumMap.put("size",innerMap); map.put("aggregation", sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("{collection_name}/_size") public ApiResponse getCollectionSize( @Context UriInfo ui, @PathParam( "collection_name" ) String collection_name, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); long size = management.getCollectionSize(this.applicationId, collection_name); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); Map innerMap = new HashMap<>(); innerMap.put(collection_name,size); sumMap.put("size",innerMap); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("collections/_size") public ApiResponse getEachCollectionSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); Map sizes = management.getEachCollectionSize(this.applicationId); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); sumMap.put("size",sizes); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @POST @Path("sia-provider") @Consumes(APPLICATION_JSON) @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, Map json, @QueryParam("callback") @DefaultValue("") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "post signin provider configuration" ); Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); SignInAsProvider signInAsProvider = null; if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { signInAsProvider = signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { signInAsProvider = signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { signInAsProvider = signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); } Preconditions.checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); signInAsProvider.saveToConfiguration( json ); return response; } // @POST // @Path("export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // // UUID jobUUID = null; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( bucketName == null ) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // json.put("organizationId", organization.getUuid()); // json.put( "applicationId",applicationId); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // catch ( Exception e ) { // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // return Response.status( SC_INTERNAL_SERVER_ERROR ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // @POST // @Path("collection/{collection_name}/export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui, // @PathParam( "collection_name" ) String collection_name ,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // UUID jobUUID = null; // String colExport = collection_name; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // //checkJsonExportProperties(json); // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // if(bucketName == null) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // // json.put( "organizationId",organization.getUuid() ); // json.put( "applicationId", applicationId); // json.put( "collectionName", colExport); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ) // .build(); // } // catch ( Exception e ) { // // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // // OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_INTERNAL_SERVER_ERROR ) // .setErrorDescription( e.getMessage() ) // .buildJSONMessage(); // // return Response.status( errorMsg.getResponseStatus() ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ) // .build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // // @Path( "imports" ) // public ImportsResource importGetJson( @Context UriInfo ui, // @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) // throws Exception { // // // return getSubResource( ImportsResource.class ).init( organization, application ); // } @GET @Path("/status") public Response getStatus() { Map statusMap = new HashMap(); EntityManager em = emf.getEntityManager( applicationId ); if ( !emf.getIndexHealth().equals( Health.RED ) ) { statusMap.put("message", "Index Health Status RED for application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } try { if ( em.getApplication() == null ) { statusMap.put("message", "Application " + applicationId + " not found"); return Response.status( SC_NOT_FOUND ).entity( statusMap ).build(); } } catch (Exception ex) { statusMap.put("message", "Error looking up application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } return Response.status( SC_OK ).entity( null ).build(); } /** * Put on application URL will restore application if it was deleted. */ @PUT @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executePut( @Context UriInfo ui, String body, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if ( applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (!SubjectUtils.isServiceAdmin()) { // require password if it exists String storedRestorePassword = restorePasswordService.getApplicationRestorePassword(applicationId); if (StringUtils.isNotEmpty(storedRestorePassword)) { // must have matching password as query parameter String suppliedRestorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (!storedRestorePassword.equals(suppliedRestorePassword)) { throw new IllegalArgumentException("Application cannot be restored without application password"); } } } management.restoreApplication( applicationId ); // not deleting password -- will be changed upon successful soft delete ApiResponse response = createApiResponse(); response.setAction( "restore" ); response.setApplication( emf.getEntityManager( applicationId ).getApplication() ); response.setParams( ui.getQueryParameters() ); return response; } /** * Caller MUST pass confirm_application_identifier that is either the UUID or the * name of the application to be deleted. Yes, this is redundant and intended to * be a protection measure to force caller to confirm that they want to do a delete. */ @DELETE @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executeDelete( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback, @QueryParam(CONFIRM_APPLICATION_IDENTIFIER) String confirmApplicationIdentifier) throws Exception { if ( application == null && applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } // If the path uses name then expect name, otherwise if they use uuid then expect uuid. if (application == null) { if (!applicationId.toString().equals( confirmApplicationIdentifier )) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application id."); } } else if (!application.getName().split( "/" )[1].equals( confirmApplicationIdentifier ) ) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application name"); } String restorePassword = null; ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (SubjectUtils.isServiceAdmin()) { restorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (StringUtils.isNotEmpty(restorePassword)) { // save password, required for future undelete if not sysadmin restorePasswordService.setApplicationRestorePassword(applicationId, restorePassword); } } management.deleteApplication( applicationId ); if (restorePassword == null) { // clear restore password restorePasswordService.removeApplicationRestorePassword(applicationId); } if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() deleted appId = {}", applicationId); } ApiResponse response = createApiResponse(); response.setAction( "delete" ); response.setApplication(emf.getEntityManager( applicationId ).getApplication()); response.setParams(ui.getQueryParameters()); if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() sending response "); } return response; } private ApplicationRestorePasswordService getApplicationRestorePasswordService() { return injector.getInstance(ApplicationRestorePasswordService.class); } } |
blob | f | f | f | blob | 0 | 4028 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/rest/src/main/java/org/apache/usergrid/rest/management/organizations/applications/ApplicationResource.java/#L63-L563 | 1 | 395 | 4028 | major | ||
| 1661 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetAgent extends Agent { //---------------------navigational members----------------------------------- // All these request objects point to the same physical request object. ConnectionRequestInterface connectionRequest_; StatementRequestInterface statementRequest_; ResultSetRequestInterface resultSetRequest_; // All these reply objects point to the same physical reply object. ConnectionReply connectionReply_; private ConnectionReply packageReply_; StatementReply statementReply_; ResultSetReply resultSetReply_; //---------------------navigational cheat-links------------------------------- // Cheat-links are for convenience only, and are not part of the conceptual model. // Warning: // Cheat-links should only be defined for invariant state data. // That is, the state data is set by the constructor and never changes. // Alias for (NetConnection) super.connection NetConnection netConnection_; // Alias for (Request) super.*Request, all in one // In the case of the NET implementation, these all point to the same physical request object. private Request request_; NetConnectionRequest netConnectionRequest_; private NetPackageRequest netPackageRequest_; private NetStatementRequest netStatementRequest_; private NetResultSetRequest netResultSetRequest_; // Alias for (Reply) super.*Reply, all in one. // In the case of the NET implementation, these all point to the same physical reply object. private Reply reply_; NetConnectionReply netConnectionReply_; private NetPackageReply netPackageReply_; private NetStatementReply netStatementReply_; private NetResultSetReply netResultSetReply_; //-----------------------------state------------------------------------------ Socket socket_; private InputStream rawSocketInputStream_; private OutputStream rawSocketOutputStream_; String server_; int port_; private int clientSSLMode_; private EbcdicCcsidManager ebcdicCcsidManager_; private Utf8CcsidManager utf8CcsidManager_; private CcsidManager currentCcsidManager_; // TODO: Remove target? Keep just one CcsidManager? //public CcsidManager targetCcsidManager_; Typdef typdef_; Typdef targetTypdef_; Typdef originalTargetTypdef_; // added to support typdef overrides private int svrcod_; int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7; int targetSqlam_ = orignalTargetSqlam_; SqlException exceptionOpeningSocket_ = null; SqlException exceptionConvertingRdbnam = null; /** * Flag which indicates that a writeChain has been started and data sent to * the server. * If true, starting a new write chain will throw a DisconnectException. * It is cleared when the write chain is ended. */ private boolean writeChainIsDirty_ = false; //---------------------constructors/finalizer--------------------------------- // Only used for testing public NetAgent(NetConnection netConnection, LogWriter logWriter) throws SqlException { super(netConnection, logWriter); this.netConnection_ = netConnection; } NetAgent(NetConnection netConnection, LogWriter netLogWriter, int loginTimeout, String server, int port, int clientSSLMode) throws SqlException { super(netConnection, netLogWriter); server_ = server; port_ = port; netConnection_ = netConnection; clientSSLMode_ = clientSSLMode; if (server_ == null) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET), "serverName"); } try { socket_ = (Socket)AccessController.doPrivileged( new OpenSocketAction(server, port, clientSSLMode_)); } catch (PrivilegedActionException e) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER), e.getException(), e.getException().getClass().getName(), server, port, e.getException().getMessage()); } // Set TCP/IP Socket Properties try { if (exceptionOpeningSocket_ == null) { socket_.setTcpNoDelay(true); // disables nagles algorithm socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2 socket_.setSoTimeout(loginTimeout * 1000); } } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION), e, e.getMessage()); } try { if (exceptionOpeningSocket_ == null) { rawSocketOutputStream_ = socket_.getOutputStream(); rawSocketInputStream_ = socket_.getInputStream(); } } catch (IOException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM), e, e.getMessage()); } ebcdicCcsidManager_ = new EbcdicCcsidManager(); utf8CcsidManager_ = new Utf8CcsidManager(); currentCcsidManager_ = ebcdicCcsidManager_; if (netConnection_.isXAConnection()) { NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_); netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_; netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, netConnection_.commBufferSize_); netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_; netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } else { netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_); netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; netResultSetRequest_ = new NetResultSetRequest(this, netConnection_.commBufferSize_); netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } } protected void resetAgent_(LogWriter netLogWriter, //CcsidManager sourceCcsidManager, //CcsidManager targetCcsidManager, int loginTimeout, String server, int port) throws SqlException { exceptionConvertingRdbnam = null; // most properties will remain unchanged on connect reset. targetTypdef_ = originalTargetTypdef_; svrcod_ = 0; // Set TCP/IP Socket Properties try { socket_.setSoTimeout(loginTimeout * 1000); } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } throw new SqlException(logWriter_, new ClientMessageId(SQLState.SOCKET_EXCEPTION), e, e.getMessage()); } } void setSvrcod(int svrcod) { if (svrcod > svrcod_) { svrcod_ = svrcod; } } void clearSvrcod() { svrcod_ = CodePoint.SVRCOD_INFO; } private int getSvrcod() { return svrcod_; } public void flush_() throws DisconnectException { sendRequest(); reply_.initialize(); } // Close socket and its streams. public void close_() throws SqlException { // can we just close the socket here, do we need to close streams individually SqlException accumulatedExceptions = null; if (rawSocketInputStream_ != null) { try { rawSocketInputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes accumulatedExceptions = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); } finally { rawSocketInputStream_ = null; } } if (rawSocketOutputStream_ != null) { try { rawSocketOutputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { rawSocketOutputStream_ = null; } } if (socket_ != null) { try { socket_.close(); } catch (IOException e) { // again {6} = 0, indicates the socket was closed. // maybe set {4} to e.getMessage(). // do this for now and but may need to modify or // add this to the message pubs. SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { socket_ = null; } } if (accumulatedExceptions != null) { throw accumulatedExceptions; } } /** * Specifies the maximum blocking time that should be used when sending * and receiving messages. The timeout is implemented by using the the * underlying socket implementation's timeout support. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @param timeout The timeout value in seconds. A value of 0 corresponds to * infinite timeout. */ protected void setTimeout(int timeout) { try { // Sets a timeout on the socket socket_.setSoTimeout(timeout * 1000); // convert to milliseconds } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.setTimeout: ignoring exception: " + se); } } } /** * Returns the current timeout value that is set on the socket. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @return The timeout value in seconds. A value of 0 corresponds to * that no timeout is specified on the socket. */ protected int getTimeout() { int timeout = 0; // 0 is default timeout for sockets // Read the timeout currently set on the socket try { timeout = socket_.getSoTimeout(); } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.getTimeout: ignoring exception: " + se); } } // Convert from milliseconds to seconds (note that this truncates // the results towards zero but that should not be a problem). timeout = timeout / 1000; return timeout; } private void sendRequest() throws DisconnectException { try { request_.flush(rawSocketOutputStream_); } catch (IOException e) { throwCommunicationsFailure(e); } } public InputStream getInputStream() { return rawSocketInputStream_; } public CcsidManager getCurrentCcsidManager() { return currentCcsidManager_; } public OutputStream getOutputStream() { return rawSocketOutputStream_; } void setInputStream(InputStream inputStream) { rawSocketInputStream_ = inputStream; } void setOutputStream(OutputStream outputStream) { rawSocketOutputStream_ = outputStream; } void throwCommunicationsFailure(Throwable cause) throws DisconnectException { //DisconnectException //accumulateReadExceptionAndDisconnect // note when {6} = 0 it indicates the socket was closed. // need to still validate any token values against message publications. accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(this, new ClientMessageId(SQLState.COMMUNICATION_ERROR), cause, cause.getMessage())); } // ----------------------- call-down methods --------------------------------- protected void markChainBreakingException_() { setSvrcod(CodePoint.SVRCOD_ERROR); } public void checkForChainBreakingException_() throws SqlException { int svrcod = getSvrcod(); clearSvrcod(); if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker { super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one. } } private void writeDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.writeDeferredReset(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } /** * Marks the agent's write chain as dirty. A write chain is dirty when data * from it has been sent to the server. A dirty write chain cannot be reset * and reused for another request until the remaining data has been sent to * the server and the write chain properly ended. * * Resetting a dirty chain will cause the new request to be appended to the * unfinished request already at the server, which will likely lead to * cryptic syntax errors. */ void markWriteChainAsDirty() { writeChainIsDirty_ = true; } private void verifyWriteChainIsClean() throws DisconnectException { if (writeChainIsDirty_) { throw new DisconnectException(this, new ClientMessageId(SQLState.NET_WRITE_CHAIN_IS_DIRTY)); } } public void beginWriteChainOutsideUOW() throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); } public void beginWriteChain(ClientStatement statement) throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); super.beginWriteChain(statement); } protected void endWriteChain() {} private void readDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.readDeferredReset(); checkForExceptions(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } protected void beginReadChain(ClientStatement statement) throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChain(statement); } protected void beginReadChainOutsideUOW() throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChainOutsideUOW(); } /** * Switches the current CCSID manager to UTF-8 */ void switchToUtf8CcsidMgr() { currentCcsidManager_ = utf8CcsidManager_; } /** * Switches the current CCSID manager to EBCDIC */ void switchToEbcdicMgr() { currentCcsidManager_ = ebcdicCcsidManager_; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11610 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.client/org/apache/derby/client/net/NetAgent.java/#L43-L550 | 2 | 1661 | 11610 | critical |
| 247 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2657 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 2 | 247 | 2657 | minor |
| 684 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class createJob_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createJob_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createJob_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6614 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/AuroraSchedulerManager.java/#L2760-L2805 | 1 | 684 | 6614 | minor |
| 4078 | {"output":"YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @HaHotStateRequired public class SensorResource extends AbstractBrooklynRestResource implements SensorApi { private static final Logger log = LoggerFactory.getLogger(SensorResource.class); @Override public List list(final String application, final String entityToken) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } List result = Lists.newArrayList(); for (AttributeSensor sensor : filter(entity.getEntityType().getSensors(), AttributeSensor.class)) { // Exclude config that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from AttributeSensor list results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } result.add(SensorTransformer.sensorSummary(entity, sensor, ui.getBaseUriBuilder())); } return result; } @Override public Map batchSensorRead(final String application, final String entityToken, final Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } Map sensorMap = Maps.newHashMap(); @SuppressWarnings("rawtypes") Iterable sensors = filter(entity.getEntityType().getSensors(), AttributeSensor.class); for (AttributeSensor sensor : sensors) { // Exclude sensors that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from current-state results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } Object value = entity.getAttribute(findSensor(entity, sensor.getName())); sensorMap.put(sensor.getName(), resolving(value).preferJson(true).asJerseyOutermostReturnValue(false).raw(raw).context(entity).timeout(Duration.ZERO).renderAs(sensor).resolve()); } return sensorMap; } protected Object get(boolean preferJson, String application, String entityToken, String sensorName, Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); AttributeSensor sensor = findSensor(entity, sensorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s' sensor '%s'", Entitlements.getEntitlementContext().user(), entity, sensor.getName()); } Object value = entity.getAttribute(sensor); return resolving(value).preferJson(preferJson).asJerseyOutermostReturnValue(true).raw(raw).context(entity).immediately(true).renderAs(sensor).resolve(); } @Override public String getPlain(String application, String entityToken, String sensorName, final Boolean raw) { return (String) get(false, application, entityToken, sensorName, raw); } @Override public Object get(final String application, final String entityToken, String sensorName, final Boolean raw) { return get(true, application, entityToken, sensorName, raw); } private AttributeSensor findSensor(Entity entity, String name) { Sensor s = entity.getEntityType().getSensor(name); if (s instanceof AttributeSensor) return (AttributeSensor) s; return new BasicAttributeSensor(Object.class, name); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void setFromMap(String application, String entityToken, Map newValues) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensors "+newValues); for (Object entry: newValues.entrySet()) { String sensorName = Strings.toString(((Map.Entry)entry).getKey()); Object newValue = ((Map.Entry)entry).getValue(); AttributeSensor sensor = findSensor(entity, sensorName); entity.sensors().set(sensor, newValue); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void set(String application, String entityToken, String sensorName, Object newValue) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensor "+sensorName+" to "+newValue); entity.sensors().set(sensor, newValue); } @Override public void delete(String application, String entityToken, String sensorName) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" deleting sensor "+sensorName); ((EntityInternal)entity).sensors().remove(sensor); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10755 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/SensorResource.java/#L46-L183 | 1 | 4078 | 10755 | major |
| 1434 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 10959 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 1 | 1434 | 10959 | major |
| 1983 | { "message": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | t | f | f | data class | 0 | 12645 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 1 | 1983 | 12645 | major | ||
| 712 | {"output": "YES I found bad smells the bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } } |
blob | long method | t | t | f | long method | blob | 0 | 6781 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 | 1 | 712 | 6781 | minor |
| 4138 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10899 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 4138 | 10899 | major |
| 2412 | { "message": "YES I found bad smells", "bad smells are:": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14403 | https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 | 1 | 2412 | 14403 | major |
| 1167 | {"message": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10186 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 1 | 1167 | 10186 | minor |
| 3812 | of the smells are contained as the code is well written. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9703 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 2 | 3812 | 9703 | minor | ||
| 1577 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 11353 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 1577 | 11353 | minor |
| 2587 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inappropriate comments 5. Lacking encapsulation 6. Inconsistent naming conventions 7. Magic numbers/constants used without explanation 8. Use of legacy code without proper attribution 9. Possible concurrency issues 10. Improper exception handling 11. Lack of modularity/separation of concerns 12. Use of static variables without proper justification 13. Inappropriate levels of abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | Long method2 Feature envy3 Duplicate code4 Inappropriate comments5 Lacking encapsulation6 Inconsistent naming conventions7 Magic numbers/constants used without explanation8 Use of legacy code without proper attribution9 Possible concurrency issues | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inappropriate comments5. Lacking encapsulation6. Inconsistent naming conventions7. Magic numbers/constants used without explanation8. Use of legacy code without proper attribution9. Possible concurrency issues | data class | 0 | 14990 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2587 | 14990 | minor |
| 76 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 1158 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 1 | 76 | 1158 | major |
| 2103 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13166 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 1 | 2103 | 13166 | minor |
| 1141 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10090 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 1 | 1141 | 10090 | minor |
| 698 | {"message":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Scanner { private final List tokens; private int currentPosition = 0; public Scanner(final List tokens) { this.tokens = tokens; } public NodeSelect scan() { return scanSelect(); } public void checkTail() { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && (item1.getNodeType() != NodeType.OPERATION || item1.getValue().length() != 0)) { currentPosition = num1; throwSyntaxError(SyntaxError.EXPECTING_END_OF_STRING); } } private NodeSelect scanSelect() { final Node node1 = ensureToken(NodeType.NAME, "select", SyntaxError.EXPECTING_SELECT); //$NON-NLS-1$ final NodeSelect select1 = new NodeSelect(); if (scanToken(NodeType.OPERATION, "*") != null) //$NON-NLS-1$ { select1.setFields(null); } else { select1.setFields(scanFieldNameList(false, NodeType.FIELD_LIST)); } while (true) { if (scanToken(NodeType.NAME, "from") != null) //$NON-NLS-1$ { if (select1.getFrom() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_FROM); } select1.setFrom(scanTableName()); continue; } if (scanToken(NodeType.NAME, "where") != null) //$NON-NLS-1$ { if (select1.getWhere() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_WHERE); } select1.setWhere(scanWhere(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getGroupBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_GROUP_BY); } select1.setGroupBy(scanFieldNameList(false, NodeType.GROUP_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "order") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getOrderBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_ORDER_BY); } select1.setOrderBy(scanFieldNameList(true, NodeType.ORDER_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "asof") != null) //$NON-NLS-1$ { if (select1.getAsOf() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_AS_OF); } select1.setAsOf(scanValue(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "mode") != null) //$NON-NLS-1$ { if (select1.getMode() != null) { currentPosition--; throwSyntaxError(SyntaxError.DUPLICATE_MODE); } select1.setMode(ScanMode()); continue; } select1.setStartOffset(node1.getStartOffset()); select1.setEndOffset(((NodeItem) tokens.get(tokens.size() - 1)).getEndOffset()); return select1; } } private Node scanWhere(final NodeTableName table) { return scanCondition4(table); } private Node scanCondition4(final NodeTableName table) { Node node1 = scanCondition3(table); NodeOrOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "or"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "||"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeOrOperator(); operator1.add(node1); } operator1.add(scanCondition3(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition3(final NodeTableName table) { Node node1 = scanCondition2(table); NodeAndOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "and"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "&&"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeAndOperator(); operator1.add(node1); } operator1.add(scanCondition2(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition2(final NodeTableName table) { Node node1 = scanToken(NodeType.NAME, "not"); //$NON-NLS-1$ if (node1 == null) { node1 = scanToken(NodeType.OPERATION, "!"); //$NON-NLS-1$ } if (node1 != null) { final Node node2 = scanCondition2(table); final Node node3 = new NodeNotOperator(node2); node3.setStartOffset(node1.getStartOffset()); node3.setEndOffset(node2.getEndOffset()); return node3; } node1 = scanToken(NodeType.NAME, "ever"); //$NON-NLS-1$ if (node1 != null) { final Node node4 = scanCondition2(table); final Node node5 = new NodeEverOperator(node4); node5.setStartOffset(node1.getStartOffset()); node5.setEndOffset(node4.getEndOffset()); return node5; } node1 = scanToken(NodeType.NAME, "never"); //$NON-NLS-1$ if (node1 != null) { final Node node6 = scanCondition2(table); final Node node7 = new NodeNotOperator(new NodeEverOperator(node6)); node7.setStartOffset(node1.getStartOffset()); node7.setEndOffset(node6.getEndOffset()); return node7; } return scanCondition1(table); } private Node scanCondition1(final NodeTableName table) { final Node node1 = scanToken(NodeType.OPERATION, "("); //$NON-NLS-1$ if (node1 != null) { final Node node2 = scanWhere(table); final Node node3 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ node2.setStartOffset(node1.getStartOffset()); node2.setEndOffset(node3.getEndOffset()); node2.setHasParantheses(true); return node2; } final NodeCondition condition1 = new NodeCondition(); Node node4 = condition1; condition1.setLeft(scanFieldName(table)); final Stack stack1 = new Stack(); while (true) { if (scanToken(NodeType.NAME, "not") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); continue; } if (scanToken(NodeType.NAME, "ever") != null) //$NON-NLS-1$ { stack1.push(NodeType.EVER); continue; } if (scanToken(NodeType.NAME, "never") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); stack1.push(NodeType.EVER); continue; } break; } while (true) { if (stack1.size() <= 0) { condition1.setCondition(scanConditionOperator(node4 != condition1)); if (condition1.getCondition() == Condition.NONE) { throwSyntaxError(SyntaxError.EXPECTING_COMPARISON_OPERATOR); } if (condition1.getCondition() == Condition.GROUP) { condition1.setRight(scanValue(table)); } else if (condition1.getCondition() == Condition.IN) { final Node node5 = ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final Node node6 = scanValueList(table); final Node node7 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ node6.setStartOffset(node5.getStartOffset()); node6.setEndOffset(node7.getEndOffset()); condition1.setRight(node6); } else if (condition1.getCondition() == Condition.UNDER) { condition1.setRight(scanValue(table)); } else { Node node8 = TryScanFieldName(); if (node8 == null) { node8 = TryScanExpression(); } if (node8 != null) { condition1.setRight(node8); } else { throwSyntaxError(SyntaxError.EXPECTING_FIELD_OR_EXPRESSION); } } node4.setStartOffset(condition1.getLeft().getStartOffset()); node4.setEndOffset(condition1.getRight().getEndOffset()); return node4; } final NodeType nodeType = stack1.pop(); if (nodeType == NodeType.NOT) { node4 = new NodeNotOperator(node4); } else if (nodeType == NodeType.EVER) { node4 = new NodeEverOperator(node4); } } } private Node scanValueList(final NodeTableName table) { final NodeValueList list1 = new NodeValueList(); do { list1.add(scanExpression(table)); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ list1.setStartOffset(list1.getItem(0).getStartOffset()); list1.setEndOffset(list1.getItem(list1.getCount() - 1).getEndOffset()); return list1; } private Node scanValue(final NodeTableName table) { final Node node = TryScanSingleValue(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); } return node; } private Node scanExpression(final NodeTableName nodeTable) { final Node node = TryScanExpression(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); return null; } return node; } private Condition scanConditionOperator(final boolean afterNotOrEver) { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && ((item1.getNodeType() == NodeType.NAME) || ((item1.getNodeType() == NodeType.OPERATION) && !afterNotOrEver))) { Condition condition1 = ConditionalOperators.find(item1.getValue()); if (condition1 == Condition.IN && scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { condition1 = Condition.GROUP; } else if (condition1 == Condition.CONTAINS && scanToken(NodeType.NAME, "words") != null) //$NON-NLS-1$ { condition1 = Condition.CONTAINS_WORDS; } if (condition1 != Condition.NONE) { return condition1; } } currentPosition = num1; if (!afterNotOrEver) { return Condition.NONE; } return Condition.EQUALS; } private NodeTableName scanTableName() { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == NodeType.NAME) { return new NodeTableName((NodeName) tokenNode); } currentPosition = savedCurrentPosition; throwSyntaxError(SyntaxError.EXPECTING_TABLE_NAME); return null; } // direction is true if each field name in the field name list can be // suffixed by an optional // direction indicator - asc or desc private NodeFieldList scanFieldNameList(final boolean direction, final NodeType nodeType) { final NodeFieldList fieldListNode = new NodeFieldList(nodeType); while (true) { final NodeFieldName fieldNameNode = scanFieldName(null); if (direction) { if (scanToken(NodeType.NAME, "asc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.ASCENDING); } else if (scanToken(NodeType.NAME, "desc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.DESCENDING); } } fieldListNode.add(fieldNameNode); /* * if the next token is not a comma operator, then the field list is * finished */ if (scanToken(NodeType.OPERATION, ",") == null) //$NON-NLS-1$ { if (fieldListNode.getCount() != 0) { /* * if the field list node is not empty, set it's start and * end offset by using the starting and ending node in the * list */ fieldListNode.setStartOffset(fieldListNode.getItem(0).getStartOffset()); fieldListNode.setEndOffset(fieldListNode.getItem(fieldListNode.getCount() - 1).getEndOffset()); } return fieldListNode; } } } private NodeFieldName scanFieldName(final NodeTableName table) { final Node node = TryScanFieldName(); if (node != null) { return (NodeFieldName) node; } throwSyntaxError(SyntaxError.EXPECTING_FIELD_NAME); return null; } private NodeMode ScanMode() { ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final NodeMode mode = new NodeMode(); do { final int pos = currentPosition; final NodeItem item = nextToken(); if ((item == null) || !(item.getNodeType().equals(NodeType.NAME))) { currentPosition = pos; throwSyntaxError(SyntaxError.EXPECTING_MODE); return null; } mode.add(item); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ mode.setStartOffset(mode.getItem(0).getStartOffset()); mode.setEndOffset(mode.getItem(mode.getCount() - 1).getEndOffset()); return mode; } private NodeItem ensureToken(final NodeType type, final String str, final SyntaxError syntaxError) { final NodeItem tokenNode = scanToken(type, str); if (tokenNode == null) { throwSyntaxError(syntaxError); } return tokenNode; } private void throwSyntaxError(final SyntaxError error) { NodeItem causeNode = null; if (currentPosition < tokens.size()) { causeNode = (NodeItem) tokens.get(currentPosition); } throw new SyntaxException(causeNode, error); } private NodeItem scanToken(final NodeType type, final String str) { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == type && str.equalsIgnoreCase(tokenNode.getValue())) { return tokenNode; } currentPosition = savedCurrentPosition; return null; } private NodeItem nextToken() { if (currentPosition < tokens.size()) { return (NodeItem) tokens.get(currentPosition++); } return null; } private Node TryScanExpression() { int num; Node node = TryScanSingleValue(); if (node == null) { return null; } while (true) { num = currentPosition; final NodeItem item = nextToken(); if (item != null) { Arithmetic none = Arithmetic.NONE; Node node2 = null; if (item.getNodeType() == NodeType.NUMBER) { none = ArithmeticalOperators.find(item.getValue().substring(0, 1)); if (none != Arithmetic.NONE) { item.setValue(item.getValue().substring(1)); node2 = item; } } else if (item.getNodeType() == NodeType.OPERATION) { none = ArithmeticalOperators.find(item.getValue()); if (none != Arithmetic.NONE) { node2 = TryScanSingleValue(); } } if ((none != Arithmetic.NONE) && (node2 != null)) { final NodeArithmetic arithmetic2 = new NodeArithmetic(); arithmetic2.setArithmetic(none); arithmetic2.setLeft(node); arithmetic2.setRight(node2); arithmetic2.setStartOffset(arithmetic2.getLeft().getStartOffset()); arithmetic2.setEndOffset(arithmetic2.getRight().getEndOffset()); node = arithmetic2; continue; } } currentPosition = num; return node; } } private Node TryScanFieldName() { Node node = null; final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (node2.getNodeType() == NodeType.NAME)) { final NodeItem item = scanToken(NodeType.OPERATION, "."); //$NON-NLS-1$ Node node3 = null; if (item != null) { node3 = nextToken(); if ((node3 != null) && (node3.getNodeType() == NodeType.NAME)) { node = new NodeFieldName((NodeName) node2, (NodeName) node3); } } else { node = new NodeFieldName((NodeName) node2); } } if (node == null) { currentPosition = pos; return null; } return node; } private Node TryScanSingleValue() { final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (((node2.getNodeType() == NodeType.NUMBER) || (node2.getNodeType() == NodeType.STRING)) || ((node2.getNodeType() == NodeType.VARIABLE) || (node2.getNodeType() == NodeType.BOOL_VALUE)))) { return node2; } currentPosition = pos; return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 6676 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/workitem/internal/wiqlparse/Scanner.java/#L9-L514 | 2 | 698 | 6676 | critical |
| 2335 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14161 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 2335 | 14161 | minor |
| 29 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 714 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 1 | 29 | 714 | minor |
| 368 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3790 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 368 | 3790 | major |
| 2668 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list 5. Data class 6. Data clump 7. Lazy class 8. Message chains 9. Primitive obsession 10. Duplicate code 11. Magic numbers 12. Shotgun surgery 13. Inconsistent variable naming 14. Unused imports 15. Unnecessary comments 16. Inconsistent use of whitespace 17. Unnecessary injection 18. Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | Long method2 Feature envy3 Large class4 Long parameter list5 Data class6 Data clump7 Lazy class8 Message chains9 Primitive obsession | t | f | f | . Long method2. Feature envy3. Large class4. Long parameter list5. Data class6. Data clump7. Lazy class8. Message chains9. Primitive obsession | blob | 0 | 15207 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 2 | 2668 | 15207 | minor |
| 128 | {"answer":"YES I found bad smells","bad smells":["Long Method","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupByMergingQueryRunnerV2 implements QueryRunner { private static final Logger log = new Logger(GroupByMergingQueryRunnerV2.class); private static final String CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION = "mergeRunnersUsingChainedExecution"; private final GroupByQueryConfig config; private final Iterable> queryables; private final ListeningExecutorService exec; private final QueryWatcher queryWatcher; private final int concurrencyHint; private final BlockingPool mergeBufferPool; private final ObjectMapper spillMapper; private final String processingTmpDir; private final int mergeBufferSize; public GroupByMergingQueryRunnerV2( GroupByQueryConfig config, ExecutorService exec, QueryWatcher queryWatcher, Iterable> queryables, int concurrencyHint, BlockingPool mergeBufferPool, int mergeBufferSize, ObjectMapper spillMapper, String processingTmpDir ) { this.config = config; this.exec = MoreExecutors.listeningDecorator(exec); this.queryWatcher = queryWatcher; this.queryables = Iterables.unmodifiableIterable(Iterables.filter(queryables, Predicates.notNull())); this.concurrencyHint = concurrencyHint; this.mergeBufferPool = mergeBufferPool; this.spillMapper = spillMapper; this.processingTmpDir = processingTmpDir; this.mergeBufferSize = mergeBufferSize; } @Override public Sequence run(final QueryPlus queryPlus, final Map responseContext) { final GroupByQuery query = (GroupByQuery) queryPlus.getQuery(); final GroupByQueryConfig querySpecificConfig = config.withOverrides(query); // CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION is here because realtime servers use nested mergeRunners calls // (one for the entire query and one for each sink). We only want the outer call to actually do merging with a // merge buffer, otherwise the query will allocate too many merge buffers. This is potentially sub-optimal as it // will involve materializing the results for each sink before starting to feed them into the outer merge buffer. // I'm not sure of a better way to do this without tweaking how realtime servers do queries. final boolean forceChainedExecution = query.getContextBoolean( CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, false ); final QueryPlus queryPlusForRunners = queryPlus .withQuery( query.withOverriddenContext(ImmutableMap.of(CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, true)) ) .withoutThreadUnsafeState(); if (QueryContexts.isBySegment(query) || forceChainedExecution) { ChainedExecutionQueryRunner runner = new ChainedExecutionQueryRunner<>(exec, queryWatcher, queryables); return runner.run(queryPlusForRunners, responseContext); } final boolean isSingleThreaded = querySpecificConfig.isSingleThreaded(); final AggregatorFactory[] combiningAggregatorFactories = new AggregatorFactory[query.getAggregatorSpecs().size()]; for (int i = 0; i < query.getAggregatorSpecs().size(); i++) { combiningAggregatorFactories[i] = query.getAggregatorSpecs().get(i).getCombiningFactory(); } final File temporaryStorageDirectory = new File( processingTmpDir, StringUtils.format("druid-groupBy-%s_%s", UUID.randomUUID(), query.getId()) ); final int priority = QueryContexts.getPriority(query); // Figure out timeoutAt time now, so we can apply the timeout to both the mergeBufferPool.take and the actual // query processing together. final long queryTimeout = QueryContexts.getTimeout(query); final boolean hasTimeout = QueryContexts.hasTimeout(query); final long timeoutAt = System.currentTimeMillis() + queryTimeout; return new BaseSequence<>( new BaseSequence.IteratorMaker>() { @Override public CloseableGrouperIterator make() { final List resources = new ArrayList<>(); try { final LimitedTemporaryStorage temporaryStorage = new LimitedTemporaryStorage( temporaryStorageDirectory, querySpecificConfig.getMaxOnDiskStorage() ); final ReferenceCountingResourceHolder temporaryStorageHolder = ReferenceCountingResourceHolder.fromCloseable(temporaryStorage); resources.add(temporaryStorageHolder); // If parallelCombine is enabled, we need two merge buffers for parallel aggregating and parallel combining final int numMergeBuffers = querySpecificConfig.getNumParallelCombineThreads() > 1 ? 2 : 1; final List> mergeBufferHolders = getMergeBuffersHolder( numMergeBuffers, hasTimeout, timeoutAt ); resources.addAll(mergeBufferHolders); final ReferenceCountingResourceHolder mergeBufferHolder = mergeBufferHolders.get(0); final ReferenceCountingResourceHolder combineBufferHolder = numMergeBuffers == 2 ? mergeBufferHolders.get(1) : null; Pair, Accumulator> pair = RowBasedGrouperHelper.createGrouperAccumulatorPair( query, false, null, config, Suppliers.ofInstance(mergeBufferHolder.get()), combineBufferHolder, concurrencyHint, temporaryStorage, spillMapper, combiningAggregatorFactories, exec, priority, hasTimeout, timeoutAt, mergeBufferSize ); final Grouper grouper = pair.lhs; final Accumulator accumulator = pair.rhs; grouper.init(); final ReferenceCountingResourceHolder> grouperHolder = ReferenceCountingResourceHolder.fromCloseable(grouper); resources.add(grouperHolder); ListenableFuture> futures = Futures.allAsList( Lists.newArrayList( Iterables.transform( queryables, new Function, ListenableFuture>() { @Override public ListenableFuture apply(final QueryRunner input) { if (input == null) { throw new ISE( "Null queryRunner! Looks to be some segment unmapping action happening" ); } ListenableFuture future = exec.submit( new AbstractPrioritizedCallable(priority) { @Override public AggregateResult call() { try ( // These variables are used to close releasers automatically. @SuppressWarnings("unused") Releaser bufferReleaser = mergeBufferHolder.increment(); @SuppressWarnings("unused") Releaser grouperReleaser = grouperHolder.increment() ) { final AggregateResult retVal = input.run(queryPlusForRunners, responseContext) .accumulate( AggregateResult.ok(), accumulator ); // Return true if OK, false if resources were exhausted. return retVal; } catch (QueryInterruptedException e) { throw e; } catch (Exception e) { log.error(e, "Exception with one of the sequences!"); throw new RuntimeException(e); } } } ); if (isSingleThreaded) { waitForFutureCompletion( query, Futures.allAsList(ImmutableList.of(future)), hasTimeout, timeoutAt - System.currentTimeMillis() ); } return future; } } ) ) ); if (!isSingleThreaded) { waitForFutureCompletion(query, futures, hasTimeout, timeoutAt - System.currentTimeMillis()); } return RowBasedGrouperHelper.makeGrouperIterator( grouper, query, new Closeable() { @Override public void close() { for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } } } ); } catch (Throwable e) { // Exception caught while setting up the iterator; release resources. for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } throw e; } } @Override public void cleanup(CloseableGrouperIterator iterFromMake) { iterFromMake.close(); } } ); } private List> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List> mergeBufferHolder; // This will potentially block if there are no merge buffers left in the pool. if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } } private void waitForFutureCompletion( GroupByQuery query, ListenableFuture> future, boolean hasTimeout, long timeout ) { try { if (queryWatcher != null) { queryWatcher.registerQuery(query, future); } if (hasTimeout && timeout <= 0) { throw new TimeoutException(); } final List results = hasTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get(); for (AggregateResult result : results) { if (!result.isOk()) { future.cancel(true); throw new ResourceLimitExceededException(result.getReason()); } } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (CancellationException e) { throw new QueryInterruptedException(e); } catch (TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } |
blob | long method, long method | t | t | f | long method, long method | blob | 0 | 1606 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/GroupByMergingQueryRunnerV2.java/#L72-L392 | 1 | 128 | 1606 | critical |
| 2077 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in Instantiator and Serializer classes) 4. Useless comments (e.g. "possible object is" and "allowed object is" in Instantiator and Serializer classes) 5. Inconsistent indentation 6. Lack of proper exception handling 7. Inadequate variable names (e.g. "className" instead of "serializerClassName" in Serializer class) 8. Incomplete documentation (e.g. there is no description of what this class is used for) 9. Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) 10. Possible violation of Open/Closed Principle (if new types of serializers or instantiators are added, changes will need to be made to this class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long method2 Feature envy3 Duplicate code (in Instantiator and Serializer classes)4 Useless comments (eg "possible object is" and "allowed object is" in Instantiator and Serializer classes)5 Inconsistent indentation6 Lack of proper exception handling7 Inadequate variable names (eg "className" instead of "serializerClassName" in Serializer class)8 Incomplete documentation (eg there is no description of what this class is used for)9 Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) | t | f | f | . Long method2. Feature envy3. Duplicate code (in Instantiator and Serializer classes)4. Useless comments (e.g. "possible object is" and "allowed object is" in Instantiator and Serializer classes)5. Inconsistent indentation6. Lack of proper exception handling7. Inadequate variable names (e.g. "className" instead of "serializerClassName" in Serializer class)8. Incomplete documentation (e.g. there is no description of what this class is used for)9. Possible violation of Single Responsibility Principle (the class seems to have multiple responsibilities, such as storing serializers and instantiators) | data class | 0 | 13052 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 2077 | 13052 | major |
| 2245 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13647 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 2245 | 13647 | major |
| 611 | { "response": "YES I found bad smells", "bad smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | 1. blob, 2. long method | t | t | f | 1. blob, 2. long method | data class | 0 | 6133 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 1 | 611 | 6133 | minor |
| 1827 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (repeated code in the methods rawBytes, rawBuffer and string) 3. Duplicate code 4. Inconsistent formatting and spacing 5. Lack of proper naming for variables and methods 6. Use of annotations without proper documentation 7. Lack of comments to explain the purpose and functionality of the methods 8. Use of raw types for Map and Object types 9. Use of unnecessary interface in RecordBuilder 10. Mutable fields in RecordBuilder 11. Use of Assert class instead of proper exception handling 12. Lack of encapsulation in the MapRecord and ObjectRecord classes 13. Inconsistent use of generic types 14. Unnecessary inheritance in the MapBackedRecord and ObjectBackedRecord classes 15. Lack of proper validation in the RecordBuilder class 16. Use of ObjectUtils and ClassUtils without proper justification 17. Inconsistent use of annotations in the fields 18. Lack of proper exception handling and error messages 19. Inconsistent and unclear method signatures 20. Misuse of the static keyword 21. Lack of proper documentation and explanation for the utility constructor 22. Lack of exception handling in the constructors 23. Lack of proper exception handling in the withId methods 24. Use of null checks instead of proper exception handling 25. Unnecessary implementation of equals and hashCode methods without proper justification 26. Code is not easily reusable and maintainable due to tight coupling and lack of abstraction. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } } |
blob | Long method 2 Feature envy (repeated code in the methods rawBytes, rawBuffer and string) 3 Duplicate code 4 Inconsistent formatting and spacing 5 Lack of proper naming for variables and methods 6 Use of annotations without proper documentation 7 Lack of comments to explain the purpose and functionality of the methods 8 Use of raw types for Map and Object types 9 Use of unnecessary interface in RecordBuilder | t | f | f | . Long method 2. Feature envy (repeated code in the methods rawBytes, rawBuffer and string) 3. Duplicate code 4. Inconsistent formatting and spacing 5. Lack of proper naming for variables and methods 6. Use of annotations without proper documentation 7. Lack of comments to explain the purpose and functionality of the methods 8. Use of raw types for Map and Object types 9. Use of unnecessary interface in RecordBuilder | blob | 0 | 12115 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 | 2 | 1827 | 12115 | minor |
| 2505 | {"result": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14667 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2505 | 14667 | critical |
| 233 | {"message":"YES I found bad smells", "bad smells are":["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NsTestPrintStream extends PrintStream { /////////////////////////////////////////////////////////////////////////////////// // // CONSTANTS // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // STATE // /////////////////////////////////////////////////////////////////////////////////// private boolean _chatty; /////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR // /////////////////////////////////////////////////////////////////////////////////// /** Construct a quiet or chatty print stream */ public NsTestPrintStream( PrintStream wrappedStream, boolean chatty ) { super( wrappedStream ); _chatty = chatty; } /////////////////////////////////////////////////////////////////////////////////// // // OVERRIDDEN BEHAVIOR // /////////////////////////////////////////////////////////////////////////////////// public PrintStream append( char c ) { if ( _chatty ) { super.append( c ); } return this; } public PrintStream append( CharSequence csq ) { if ( _chatty ) { super.append( csq ); } return this; } public PrintStream append( CharSequence csq, int start, int end ) { if ( _chatty ) { super.append( csq, start, end ); } return this; } public boolean checkError() { return super.checkError(); } protected void clearError() { super.clearError(); } public void close() { super.close(); } public void flush() { super.flush(); } public void print( boolean b ) { if ( _chatty ) { super.print( b ); } } public void print( char c ) { if ( _chatty ) { super.print( c ); } } public void print( int i ) { if ( _chatty ) { super.print( i ); } } public void print( long l ) { if ( _chatty ) { super.print( l ); } } public void print( float f ) { if ( _chatty ) { super.print( f ); } } public void print( double d ) { if ( _chatty ) { super.print( d ); } } public void print( char[] s ) { if ( _chatty ) { super.print( s ); } } public void print( String s ) { if ( _chatty ) { super.print( s ); } } public void print( Object obj ) { if ( _chatty ) { super.print( obj ); } } public void println() { if ( _chatty ) { super.println(); } } public void println( boolean x ) { if ( _chatty ) { super.println( x ); } } public void println( char x ) { if ( _chatty ) { super.println( x ); } } public void println( int x ) { if ( _chatty ) { super.println( x ); } } public void println( long x ) { if ( _chatty ) { super.println( x ); } } public void println( float x ) { if ( _chatty ) { super.println( x ); } } public void println( double x ) { if ( _chatty ) { super.println( x ); } } public void println( char[] x ) { if ( _chatty ) { super.println( x ); } } public void println( String x ) { if ( _chatty ) { super.println( x ); } } public void println( Object x ) { if ( _chatty ) { super.println( x ); } } public PrintStream printf( String format, Object... args ) { if ( _chatty ) { super.printf( format, args ); } return this; } public PrintStream printf( Locale l, String format, Object... args ) { if ( _chatty ) { super.printf( l, format, args ); } return this; } public PrintStream format( String format, Object... args ) { if ( _chatty ) { super.format( format, args ); } return this; } public PrintStream format( Locale l, String format, Object... args ) { if ( _chatty ) { super.format( l, format, args ); } return this; } public void write( byte[] buf, int off, int len ) { if ( _chatty ) { super.write( buf, off, len ); } } public void write( int b ) { if ( _chatty ) { super.write( b ); } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2549 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.tests/org/apache/derbyTesting/system/nstest/NsTestPrintStream.java/#L31-L127 | 2 | 233 | 2549 | minor |
| 504 | {"response": "YES I found bad smells", "bad smells are:":["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 5124 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 2 | 504 | 5124 | minor |
| 2160 | YES I found bad smells 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13321 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 2160 | 13321 | major |
| 1961 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Parallel Inheritance Hierarchies 4. Large Class 5. Direct Use of Raw Types 6. Unused or Redundant Code 7. Excessive Indentation 8. Lack of Encapsulation 9. Inappropriate Intimacy 10. Incomplete Library Class 11. Spaghetti Code 12. Internal Duplication 13. Inappropriate Information 14. Free Rider 15. Data Class 16. Serial Killer 17. Undisciplined Parallel Inheritance Hierarchies 18. Repeating Yourself 19. Message Chains 20. Switch Statements 21. Primitive Obsession 22. Dead Code 23. Shotgun Surgery 24. Inconsistent Formatting 25. Poor Naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public class SingleThreadAccessCheckingTypeSerializer extends TypeSerializer { private static final long serialVersionUID = 131020282727167064L; private final SingleThreadAccessChecker singleThreadAccessChecker; private final TypeSerializer originalSerializer; public SingleThreadAccessCheckingTypeSerializer(TypeSerializer originalSerializer) { this.singleThreadAccessChecker = new SingleThreadAccessChecker(); this.originalSerializer = originalSerializer; } @Override public boolean isImmutableType() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.isImmutableType(); } } @Override public TypeSerializer duplicate() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializer<>(originalSerializer.duplicate()); } } @Override public T createInstance() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.createInstance(); } } @Override public T copy(T from) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from); } } @Override public T copy(T from, T reuse) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from, reuse); } } @Override public int getLength() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.getLength(); } } @Override public void serialize(T record, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.serialize(record, target); } } @Override public T deserialize(DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(source); } } @Override public T deserialize(T reuse, DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(reuse, source); } } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.copy(source, target); } } @Override public boolean equals(Object obj) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return obj == this || (obj != null && obj.getClass() == getClass() && originalSerializer.equals(obj)); } } @Override public int hashCode() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.hashCode(); } } @Override public TypeSerializerSnapshot snapshotConfiguration() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializerSnapshot<>(this); } } public static class SingleThreadAccessCheckingTypeSerializerSnapshot extends CompositeTypeSerializerSnapshot> { @SuppressWarnings({"unchecked", "unused"}) public SingleThreadAccessCheckingTypeSerializerSnapshot() { super((Class>) (Class) SingleThreadAccessCheckingTypeSerializer.class); } SingleThreadAccessCheckingTypeSerializerSnapshot(SingleThreadAccessCheckingTypeSerializer serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return 1; } @Override protected TypeSerializer[] getNestedSerializers(SingleThreadAccessCheckingTypeSerializer outerSerializer) { return new TypeSerializer[] { outerSerializer.originalSerializer }; } @SuppressWarnings("unchecked") @Override protected SingleThreadAccessCheckingTypeSerializer createOuterSerializerWithNestedSerializers( TypeSerializer[] nestedSerializers) { return new SingleThreadAccessCheckingTypeSerializer<>((TypeSerializer) nestedSerializers[0]); } } private void writeObject(ObjectOutputStream outputStream) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { outputStream.defaultWriteObject(); } } private static class SingleThreadAccessChecker implements Serializable { private static final long serialVersionUID = 131020282727167064L; private transient AtomicReference currentThreadRef = new AtomicReference<>(); SingleThreadAccessCheck startSingleThreadAccessCheck() { assert(currentThreadRef.compareAndSet(null, Thread.currentThread())) : "The checker has concurrent access from " + currentThreadRef.get(); return new SingleThreadAccessCheck(currentThreadRef); } private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { inputStream.defaultReadObject(); currentThreadRef = new AtomicReference<>(); } } private static class SingleThreadAccessCheck implements AutoCloseable { private final AtomicReference currentThreadRef; private SingleThreadAccessCheck(AtomicReference currentThreadRef) { this.currentThreadRef = currentThreadRef; } @Override public void close() { assert(currentThreadRef.compareAndSet(Thread.currentThread(), null)) : "The checker has concurrent access from " + currentThreadRef.get(); } } } |
blob | Long Method2 Feature Envy3 Parallel Inheritance Hierarchies4 Large Class5 Direct Use of Raw Types6 Unused or Redundant Code7 Excessive Indentation8 Lack of Encapsulation9 Inappropriate Intimacy | t | f | f | . Long Method2. Feature Envy3. Parallel Inheritance Hierarchies4. Large Class5. Direct Use of Raw Types6. Unused or Redundant Code7. Excessive Indentation8. Lack of Encapsulation9. Inappropriate Intimacy | blob | 0 | 12584 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/SingleThreadAccessCheckingTypeSerializer.java/#L31-L203 | 2 | 1961 | 12584 | minor |
| 2514 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14693 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 2514 | 14693 | minor |
| 520 | {"message":"YES, I found bad smells","the bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 5405 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 2 | 520 | 5405 | critical |
| 242 | { "output": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 242 | 2644 | major |
| 2261 | {"message": "YES I found bad smells", "the bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 13717 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 1 | 2261 | 13717 | major |
| 1018 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9334 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 1018 | 9334 | major |
| 3653 | { protected int[][] values; protected int maxValue; public ArrayImageSource( int width, int height, int[][] values ) { super( width, height ); this.values = values; public int getRGB( int x, int y ) { return values[x][y]; } YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 3653 | 8313 | minor |
| 521 | {"error": "Sorry, unable to analyze Java code without the actual code provided."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator> iterator() { return immutableComparatorRegistry.iterator(); } |
feature envy | Not specified | f | f | f | false | 0 | 5410 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/registries/ImmutableComparatorRegistry.java/#L148-L152 | 1 | 521 | 5410 | major | |
| 2543 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14787 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 1 | 2543 | 14787 | minor |
| 2194 | {"NO, I did not find any bad smell." : ""} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | ""} | f | f | f | ""} | blob | 0 | 13479 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 1 | 2194 | 13479 | minor |
| 2641 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15144 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2641 | 15144 | minor |
| 1788 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent naming conventions 5. Magic numbers 6. Useless comments 7. Misplaced responsibilities 8. Data clumps 9. Poor exception handling 10. Inadequate testing 11. Unused variables 12. Code complexity 13. Inefficient code 14. Poor variable and method naming 15. Insufficient encapsulation 16. Redundant code 17. Unnecessary use of volatile 18. Useless constructors 19. Misuse of assertions 20. Unnecessary use of interfaces 21. Unnecessary use of abstract class 22. Inadequate logging 23. Poor resource management 24. Overuse of conditionals and loops 25. Lack of proper separation of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } } |
blob | Long method2 Feature envy3 Duplicated code4 Inconsistent naming conventions 5 Magic numbers 6 Useless comments 7 Misplaced responsibilities 8 Data clumps 9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Duplicated code4. Inconsistent naming conventions 5. Magic numbers 6. Useless comments 7. Misplaced responsibilities 8. Data clumps 9. Poor exception handling | blob | 0 | 11983 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 | 2 | 1788 | 11983 | major |
| 2898 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2137 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 1 | 2898 | 2137 | critical | ||
| 344 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | f | f | f | data class | 0 | 3516 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 344 | 3516 | minor | ||
| 1849 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12187 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 1849 | 12187 | major |
| 2399 | YES I found bad smells The bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 14378 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 2 | 2399 | 14378 | minor |
| 2141 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13266 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 2141 | 13266 | major |
| 811 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7650 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 2 | 811 | 7650 | minor |
| 266 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2878 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 2 | 266 | 2878 | minor |
| 2608 | YES I found bad smells. The bad smells are: 1. Long method 2. Switch statement 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LogTransformer extends Transformer { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public Object transformRow(Map row, Context ctx) { String expr = ctx.getEntityAttribute(LOG_TEMPLATE); String level = ctx.replaceTokens(ctx.getEntityAttribute(LOG_LEVEL)); if (expr == null || level == null) return row; if ("info".equals(level)) { if (log.isInfoEnabled()) log.info(ctx.replaceTokens(expr)); } else if ("trace".equals(level)) { if (log.isTraceEnabled()) log.trace(ctx.replaceTokens(expr)); } else if ("warn".equals(level)) { if (log.isWarnEnabled()) log.warn(ctx.replaceTokens(expr)); } else if ("error".equals(level)) { if (log.isErrorEnabled()) log.error(ctx.replaceTokens(expr)); } else if ("debug".equals(level)) { if (log.isDebugEnabled()) log.debug(ctx.replaceTokens(expr)); } return row; } public static final String LOG_TEMPLATE = "logTemplate"; public static final String LOG_LEVEL = "logLevel"; } |
blob | Long method2 Switch statement3 Feature envy | t | f | f | . Long method2. Switch statement3. Feature envy | blob | 0 | 15032 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/LogTransformer.java/#L35-L67 | 2 | 2608 | 15032 | minor |
| 785 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LayoutContext { /** * An {@link LayoutContext} notifies registered listeners about changes to * the layout algorithm using this property name. */ public static final String LAYOUT_ALGORITHM_PROPERTY = "layoutAlgorithm"; private ObjectProperty layoutAlgorithmProperty = new SimpleObjectProperty<>( this, LAYOUT_ALGORITHM_PROPERTY); private Graph graph; private final List postLayoutPass = new ArrayList<>(); private final List preLayoutPass = new ArrayList<>(); private final List layoutFilters = new ArrayList<>(); /** * Adds the given ILayoutFilter to this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to add to this context. */ public void addLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.add(layoutFilter); } /** * Applies the layout algorithm of this LayoutContext. The clean flag is * passed-in to the layout algorithm to indicate whether the context changed * significantly since the last layout pass. * * @param clear * true to indicate that the algorithm has to fully * re-compute the layout, otherwise false. */ public void applyLayout(boolean clear) { ILayoutAlgorithm layoutAlgorithm = layoutAlgorithmProperty.get(); if (layoutAlgorithm != null) { preLayout(); layoutAlgorithm.applyLayout(this, clear); postLayout(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run after the layout pass. Should not be * called by clients. */ public void postLayout() { for (Runnable r : new ArrayList<>(postLayoutPass)) { r.run(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run before the layout pass. Should not be * called by clients. */ public void preLayout() { for (Runnable r : preLayoutPass) { r.run(); } } /** * Returns the graph that is to be layouted. * * @return The {@link Graph} that is to be layouted. */ public Graph getGraph() { return graph; } /** * Sets the graph that is to be layouted by this context. * * @param graph * The {@link Graph} to layout. */ public void setGraph(Graph graph) { // TODO: we should not allow to pass in null here. Instead we should // guard ourselves against null. if (graph == null) { graph = new Graph(); } this.graph = graph; } /** * Returns all the nodes that should be laid out. Replacing elements in the * returned array does not affect this context. * * @return array of nodes to lay out */ // TODO: remove this (algorithms should use getGraph().getNodes()) public Node[] getNodes() { ObservableList nodes = graph.getNodes(); List layoutRelevantNodes = new ArrayList<>(); for (Node n : nodes) { if (!isLayoutIrrelevant(n)) { layoutRelevantNodes.add(n); } } return layoutRelevantNodes.toArray(new Node[] {}); } /** * Returns all the connections between nodes that should be laid out. * Replacing elements in the returned array does not affect this context. * * @return array of connections between nodes */ public Edge[] getEdges() { ObservableList edges = graph.getEdges(); List layoutRelevantEdges = new ArrayList<>(); for (Edge e : edges) { if (!isLayoutIrrelevant(e)) { layoutRelevantEdges.add(e); } } return layoutRelevantEdges.toArray(new Edge[] {}); } /** * Returns the static layout algorithm used to layout a newly initialized * graph or after heavy changes to it. * * @return The layout algorithm that is used by this {@link LayoutContext}. */ public ILayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithmProperty.get(); } /** * Returns true when the given {@link Edge} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param edge * The {@link Edge} in question. * @return true when the given {@link Edge} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Edge edge) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(edge)) { return true; } } return false; } /** * Returns true when the given {@link Node} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param nodeLayout * The {@link Node} in question. * @return true when the given {@link Node} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Node nodeLayout) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(nodeLayout)) { return true; } } return false; } /** * A property representing the layout algorithm used by this * {@link LayoutContext}. * * @see #getLayoutAlgorithm() * @see #setLayoutAlgorithm(ILayoutAlgorithm) * * @return A property named {@link #LAYOUT_ALGORITHM_PROPERTY}. */ public ObjectProperty layoutAlgorithmProperty() { return layoutAlgorithmProperty; }; /** * Removes the given ILayoutFilter from this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to remove to this context. */ public void removeLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.remove(layoutFilter); } /** * Adds the given {@link Runnable} to the list of runnables which are called * when this {@link LayoutContext} is asked to apply all changes made to its * elements to the display. * * @param runnable * A {@link Runnable} called whenever this context is asked to * apply all changes made to its elements to the display. */ public void schedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!postLayoutPass.contains(runnable)) { postLayoutPass.add(runnable); } } /** * Adds the given {@link Runnable} to the list of {@link Runnable}s which * are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to add to the list of {@link Runnable}s * which are executed before applying a layout. */ public void schedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!preLayoutPass.contains(runnable)) { preLayoutPass.add(runnable); } } /** * Sets the layout algorithm for this context. * * @param algorithm * The new {@link ILayoutAlgorithm} for this * {@link LayoutContext}. */ public void setLayoutAlgorithm(ILayoutAlgorithm algorithm) { layoutAlgorithmProperty.set(algorithm); } /** * Removes the given {@link Runnable} from the list of runnables which are * called when this {@link LayoutContext} is asked to apply all changes made * to its elements to the display. * * @param runnable * The {@link Runnable} that should no longer get called when * flushing changes. */ public void unschedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (postLayoutPass.contains(runnable)) { postLayoutPass.remove(runnable); } } /** * Removes the given {@link Runnable} from the list of {@link Runnable}s * which are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to remove from the list of * {@link Runnable}s which are executed before applying a layout. */ public void unschedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (preLayoutPass.contains(runnable)) { preLayoutPass.remove(runnable); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7497 | https://github.com/eclipse/gef/blob/8f2649b90ab14a1bb010188036d4eedf7586e123/org.eclipse.gef.layout/src/org/eclipse/gef/layout/LayoutContext.java/#L35-L315 | 1 | 785 | 7497 | minor |
| 106 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1407 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 | 2 | 106 | 1407 | minor |
| 4412 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 11683 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 4412 | 11683 | minor |
| 758 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 7065 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 758 | 7065 | minor |
| 4282 | YES, I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11274 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 2 | 4282 | 11274 | minor |
| 165 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConfigurationListener extends Phase implements org.osgi.service.cm.ConfigurationListener { public static class Builder { public Builder(ContainerState containerState) { _containerState = containerState; } public Builder component(Component component) { _component = component; return this; } public ConfigurationListener build() { Objects.requireNonNull(_component); return new ConfigurationListener(_containerState, _component); } private Component _component; private final ContainerState _containerState; } protected ConfigurationListener( ContainerState containerState, Component component) { super(containerState, component); _component = component; _log = containerState.containerLogs().getLogger(getClass()); } @Override public boolean close() { try (Syncro open = syncro.open()) { if (_listenerService != null) { _listenerService.unregister(); _listenerService = null; } return next.map( next -> { submit(next.closeOp(), next::close).onFailure( f -> { _log.error(l -> l.error("CCR Failure in configuration listener close on {}", next, f)); error(f); } ); return true; } ).orElse(true); } } @Override public Op closeOp() { return Op.of(Mode.CLOSE, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public void configurationEvent(ConfigurationEvent event) { next.map(next -> (Component)next).ifPresent( next -> next.configurationTemplates().stream().filter( t -> Predicates.isMatchingConfiguration(event).test(t) ).findFirst().ifPresent( t -> { String eventString = Arrays.asList(event.getPid(), event.getFactoryPid(), type(event)).toString(); Promise result = containerState.submit( Op.of(Mode.OPEN, Type.CONFIGURATION_EVENT, eventString), () -> { _log.debug(l -> l.debug("CCR Event {} matched {} because of {}", eventString, _component.template().name, _component.template().configurations)); processEvent(next, t, event); return true; } ); try { result.getValue(); } catch (Exception e) { Throw.exception(e); } } ) ); } @Override public boolean open() { try (Syncro open = syncro.open()) { if (containerState.bundleContext() == null) { // this bundle was already removed return false; } Dictionary properties = new Hashtable<>(); properties.put("name", toString()); properties.put(Constants.SERVICE_DESCRIPTION, "Aries CDI - Configuration Listener for " + containerState.bundle()); properties.put(Constants.SERVICE_VENDOR, "Apache Software Foundation"); _listenerService = containerState.bundleContext().registerService( org.osgi.service.cm.ConfigurationListener.class, this, properties); return next.map(next -> (Component)next).map( component -> { submit(component.openOp(), component::open).then( s -> { component.configurationTemplates().stream().filter( ct -> Objects.nonNull(ct.pid) ).forEach( template -> { if (template.maximumCardinality == MaximumCardinality.ONE) { containerState.findConfig(template.pid).ifPresent( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, null, c.getPid())) ); } else { containerState.findConfigs(template.pid, true).ifPresent( arr -> Arrays.stream(arr).forEach( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, c.getFactoryPid(), c.getPid())) ) ); } } ); return s; }, f -> { _log.error(l -> l.error("CCR Failure during configuration start on {}", next, f.getFailure())); error(f.getFailure()); } ); return true; } ).orElse(true); } } @Override public Op openOp() { return Op.of(Mode.OPEN, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public String toString() { return Arrays.asList(getClass().getSimpleName(), _component).toString(); } private void processEvent(Component component, ConfigurationTemplateDTO t, ConfigurationEvent event) { boolean required = t.policy == ConfigurationPolicy.REQUIRED; boolean single = t.maximumCardinality == MaximumCardinality.ONE; switch (event.getType()) { case ConfigurationEvent.CM_DELETED: component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { if (!required) { instance.configurations.removeIf( c -> c.template == t ); submit(instance.openOp(), instance::open); } else { component.instances().remove(instance); } return s; } ); } ); return; case ConfigurationEvent.CM_LOCATION_CHANGED: break; case ConfigurationEvent.CM_UPDATED: if (!single && !component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> event.getPid().equals(instance.pid) ).findFirst().isPresent()) { ExtendedComponentInstanceDTO instance = new ExtendedComponentInstanceDTO( containerState, _component.activatorBuilder()); instance.activations = new CopyOnWriteArrayList<>(); instance.configurations = new CopyOnWriteArrayList<>(); instance.pid = event.getPid(); instance.references = new CopyOnWriteArrayList<>(); instance.template = component.template(); component.instances().add(instance); } containerState.findConfig(event.getPid()).ifPresent( configuration -> { ExtendedConfigurationDTO configurationDTO = new ExtendedConfigurationDTO(); configurationDTO.configuration = configuration; configurationDTO.pid = configuration.getPid(); configurationDTO.properties = Maps.of(configuration.getProcessedProperties(event.getReference())); configurationDTO.template = t; component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { instance.configurations.removeIf(c -> c.template == t); instance.configurations.add(configurationDTO); submit(instance.openOp(), instance::open); return s; } ); } ); } ); break; } } private String type(ConfigurationEvent event) { if (event.getType() == ConfigurationEvent.CM_DELETED) return "DELETED"; if (event.getType() == ConfigurationEvent.CM_LOCATION_CHANGED) return "LOCATION_CHANGED"; if (event.getType() == ConfigurationEvent.CM_UPDATED) return "UPDATED"; throw new IllegalArgumentException("CM Event type " + event.getType()); } private volatile ServiceRegistration _listenerService; private final Component _component; private final Logger _log; } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2008 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/ConfigurationListener.java/#L42-L310 | 1 | 165 | 2008 | critical |
| 1712 | YES I found bad smells The bad smells are: 1. Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | t | f | f | . Duplicated code (methods to get and set bytesWritten, recordsWritten, writeTime) | data class | 0 | 11772 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1712 | 11772 | minor |
| 1629 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11503 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 1629 | 11503 | critical |
| 611 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 6133 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 611 | 6133 | minor |
| 1841 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 12150 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 1841 | 12150 | critical |
| 111 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1461 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 111 | 1461 | major |
| 1396 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10852 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 2 | 1396 | 10852 | minor |
| 4976 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 13623 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 1 | 4976 | 13623 | major |
| 744 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | blob | 0 | 7006 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 2 | 744 | 7006 | critical |
| 132 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 1631 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 1 | 132 | 1631 | critical |
| 2431 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14458 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 2431 | 14458 | minor |
| 1534 | {"response": "YES I found bad smells", "bad smells are: \n1. Long method, \n2. Feature envy, \n3. Data class, \n4. Shotgun surgery, \n5. Message Chains, \n6. Inappropriate intimacy, \n7. Middle Man, \n8. Comments, \n9. Long parameter list, \n10. Temporary Field, \n11. Refused Bequest, \n12. Primitive Obsession, \n13. Speculative Generality, \n14. Lazy Class, \n15. Parallel Inheritance Hierarchies, \n16. Large Class, \n17. Switch Statements, \n18. Divergent change, \n19. Shotgun surgery, \n20. Feature Envy, \n21. Inappropriate Intimacy, \n22. The Blob, \n23. Functional Decomposition, \n24. Frequent Pushes and Pops, \n25. Inappropriate exposure, \n26. Randomness, \n27. Convoluted Code, \n28. Excessive Use of Literals, \n29. Hard to Understand Code, \n30. Inconsistent Names, \n31. Deeply Nested Conditional logic, \n32. Middle Man, \n33. Contrived Complexity, \n34. Functional Decomposition, \n35. Solution Sprawl, \n36. Hard to Test Code, \n37. Inconsistent Naming, \n38. Uncommunicative Naming, \n39. Unencapsulated Collection, \n40. Multiple Languages, \n41. Oddball Solution, \n42. Forced Design, \n43. Spaghetti Code, \n44. Object Orgy, \n45. Autogenerated Hell, \n46. Interface bloat, \n47. Amenities, \n48. Special Case, \n49. Magic Constants, \n50. Duplication, \n51. Lazy Class, \n52. Switch Statements, \n53. Data Class, \n54. Broken Modularity, \n55. Cyclic Complexity, \n56. Imperative Code, \n57. Layering, \n58. Cyclomatic Complexity, \n59. Dead Code, \n60. Hard-Coded Strings, \n61. Duplicate Code, \n62. Feature Envy, \n63. God Object, \n64. Inappropriate Abstraction, \n65. Primitive Obsession, \n66. Dead Code, \n67. Refused Bequest, \n68. God Class, \n69. Spaghetti Code, \n70. Copy-Paste Programming, \n71. Cylindrical Dependency, \n72. Code Bloat, \n73. Future Proofing, \n74. Mutable Data, \n75. Sensitive Equality, \n76. Complex Code, \n77. Deadwood, \n78. Detail Envy, \n79. Global Constants, \n80. Obscured Intent, \n81. Orphan Comments, \n82. Lava Flow, \n83. Speculative Generality, \n84. Base Exception, \n85. Excess Quiet, \n86. Hard to Understand Code, \n87. Inappropriate Intimacy, \n88. Internal Getter-Setter, \n89. Middle Man, \n90. Too Cleverly Designed Code, \n91. Large Class, \n92. Primitive Obsession, \n93. Swiss Army Knife, \n94. Wide Interface, \n95. External Duplication, \n96. Variable Mutability, \n97. Wanted Behavior, \n98. Data Class, \n99. Shotgun Surgery, \n100. Message Chains, \n101. Feature Envy, \n102. Inappropriate Intimacy, \n103. Middle Man, \n104. Long Method, \n105. Long Parameter List, \n106. Data Class, \n107. Switch Statements, \n108. Divergent Change, \n109. Shotgun Surgery, \n110. Feature Envy, \n111. Inappropriate Intimacy, \n112. Inappropriate Intimacy, \n113. Primitive Obsession, \n114. Speculative Generality, \n115. Temporary Field, \n116. Long Method, \n117. Feature Envy, \n118. Primitive Obsession, \n119. Inconsistent Names, \n120. Middle Man, \n121. Switch Statements, \n122. Long Method, \n123. Feature Envy, \n124. Long Method, \n125. Feature Envy, \n126. Inappropriate Intimacy, \n127. Classroom, \n128. Brain Method, \n129. Data Clumps, \n130. Feature Envy, \n131. Middle Man, \n132. Data Clumps, \n133. Feature Envy, \n134. Data Clumps, \n135. Middle Man, \n136. Data Clumps, \n137. Data Clumps, \n138. Middle Man, \n139. Data Clumps, \n140. Middle Man, \n141. Data Clumps, \n142. Feature Envy, \n143. Middle Man, \n144. Brain Method, \n145. Middle Man, \n146. Message Chains, \n147. Feature Envy, \n148. Data Clumps, \n149. Feature Envy, \n150. Middle Man, \n151. Brain Method, \n152. Data Clumps, \n153. Feature Envy, \n154. Data Class, \n155. Switch Statements, \n156. Data Class, \n157. Data Class, \n158. Primitive Obsession, \n159. Comments, \n160. Comments, \n161. Comments, \n162. Comments, \n163. Comments, \n164. Comments, \n165. Comments, \n166. Comments, \n167. Comments, \n168. Comments, \n169. Comments, \n170. Comments, \n171. Comments, \n172. Comments, \n173. Comments, \n174. Comments, \n175. Comments, \n176. Comments, \n177. Comments, \n178. Comments, \n179. Comments, \n180. Comments, \n181. Comments, \n182. Comments, \n183. Comments, \n184. Comments, \n185. Comments, \n186. Comments, \n187. Comments, \n188. Comments, \n189. Comments, \n190. Comments, \n191. Comments, \n192. Comments, \n193. Comments, \n194. Comments, \n195. Comments, \n196. Comments, \n197. Comments, \n198. Comments, \n199. Comments, \n200. Comments, \n201. Comments, \n202. Comments, \n203. Comments, \n204. Comments, \n205. Comments, \n206. Comments, \n207. Comments, \n208. Comments, \n209. Comments, \n210. Comments, \n211. Comments, \n212. Comments, \n213. Comments, \n214. Comments, \n215. Comments, \n216. Comments, \n217. Comments, \n218. Comments, \n219. Comments, \n220. Comments, \n221. Comments, \n222. Comments, \n223. Comments, \n224. Comments, \n225. Comments, \n226. Comments, \n227. Comments, \n228. Comments, \n229. Comments, \n230. Comments, \n231. Comments, \n232. Comments, \n233. Comments, \n234. Comments" : ""} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportsAwareClipboardAction extends TextEditorAction { public static class Factory implements IClipboardActionFactory { @Inject private MembersInjector injector; @Override public TextEditorAction create(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) { ImportsAwareClipboardAction action = new ImportsAwareClipboardAction(bundle, prefix, editor, operationCode); injector.injectMembers(action); return action; } } private static final XbaseClipboardTransfer TRANSFER_INSTANCE = new XbaseClipboardTransfer(); private final int operationCode; private ITextOperationTarget textOperationTarget; private @Inject ImportsUtil importsUtil; /** * Creates the action. * * @param bundle * the resource bundle * @param prefix * a prefix to be prepended to the various resource keys (described in ResourceAction * constructor), or null if none * @param editor * the text editor. May not be null. * @param operationCode * the operation code */ public ImportsAwareClipboardAction(ResourceBundle bundle, String prefix, ITextEditor editor, final int operationCode) { super(bundle, prefix, editor); this.operationCode = operationCode; if (operationCode == ITextOperationTarget.CUT) { setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); } else if (operationCode == ITextOperationTarget.COPY) { setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); } else if (operationCode == ITextOperationTarget.PASTE) { setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); } else { Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$ } update(); } protected void internalDoOperation() { if (operationCode == ITextOperationTarget.PASTE) { doPasteWithImportsOperation(); } else { doCutCopyWithImportsOperation(); } } private void doCutCopyWithImportsOperation() { try { final XbaseClipboardData cbData = createClipboardData(); if (cbData != null ) { ClipboardUtil.clipboardOperation(new Function() { @Override public Boolean apply(Clipboard clipboard) { Map payload = newLinkedHashMap(); payload.put(cbData, TRANSFER_INSTANCE); TextTransfer textTransfer = TextTransfer.getInstance(); String textData = (String) clipboard.getContents(textTransfer); if (textData == null || textData.isEmpty()) { // StyledText copied any data to ClipBoard return Boolean.FALSE; } payload.put(textData, textTransfer); RTFTransfer rtfTransfer = RTFTransfer.getInstance(); String rtfData = (String) clipboard.getContents(rtfTransfer); if (rtfData != null && !rtfData.isEmpty()) { payload.put(rtfData, rtfTransfer); } List datas = newArrayList(); List dataTypes = newArrayList(); for (Entry entry : payload.entrySet()) { datas.add(entry.getKey()); dataTypes.add(entry.getValue()); } try { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } return Boolean.FALSE; } } }); } } finally { textOperationTarget.doOperation(operationCode); } } private void doPasteWithImportsOperation() { XbaseClipboardData xbaseClipboardData = ClipboardUtil .clipboardOperation(new Function() { @Override public XbaseClipboardData apply(Clipboard input) { Object content = input.getContents(TRANSFER_INSTANCE); if (content instanceof XbaseClipboardData) { return (XbaseClipboardData) content; } return null; } }); JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent(); String textFromClipboard = ClipboardUtil.getTextFromClipboard(); XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor)); if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) { doPasteXbaseCode(xbaseClipboardData, addImports); } else if (javaImportsContent != null) { doPasteJavaCode(textFromClipboard, javaImportsContent, addImports); } else { textOperationTarget.doOperation(operationCode); } } /** * Should not add imports when pasting into a {@link XStringLiteral} or Comments (except of JavaDoc) * * @param document * - {@link IDocument} to work with * @param caretOffset * - current caret offset */ protected boolean shouldAddImports(IDocument document, int caretOffset) { if (caretOffset == 0) { return true; } String typeRight = IDocument.DEFAULT_CONTENT_TYPE; String typeLeft = IDocument.DEFAULT_CONTENT_TYPE; try { typeRight = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset, false); typeLeft = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset > 0 ? caretOffset - 1 : caretOffset, false); } catch (BadLocationException exception) { // Should not happen } if (COMMENT_PARTITION.equals(typeRight) || STRING_LITERAL_PARTITION.equals(typeRight) || SL_COMMENT_PARTITION.equals(typeRight) || "__rich_string".equals(typeRight)) { if (typeLeft.equals(typeRight)) return false; } return true; } private int caretOffset(final XtextEditor xtextEditor) { ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer(); int caretOffset = sourceViewer.getTextWidget().getCaretOffset(); if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; caretOffset = extension.widgetOffset2ModelOffset(caretOffset); } return caretOffset; } private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(), xbaseClipboardData.getExtensionImports(), getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(), new String[] {}, getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private boolean sameTarget(XbaseClipboardData xbaseClipboardData) { IEditorInput editorInput = getTextEditor().getEditorInput(); if (editorInput == null) { return false; } return xbaseClipboardData.getSourceIndentifier().equals(editorInput.toString()); } private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.readOnly(new IUnitOfWork() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple, Set, Set> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; } private IXtextDocument getXtextDocument() { XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); IXtextDocument document = xtextEditor.getDocument(); return document; } @Override public void update() { super.update(); if (isModifyOperation() && !canModifyEditor()) { setEnabled(false); return; } ITextEditor editor = getTextEditor(); if (textOperationTarget == null && editor != null) textOperationTarget = editor.getAdapter(ITextOperationTarget.class); boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode())); setEnabled(isEnabled); } private int getOperationCode() { return operationCode; } @Override public void run() { if (textOperationTarget == null) return; ITextEditor editor = getTextEditor(); if (editor == null) return; if (isModifyOperation() && !validateEditorInputState()) return; BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { internalDoOperation(); } }); } private boolean isModifyOperation() { return operationCode != ITextOperationTarget.COPY; } private Shell getShell() { ITextEditor editor = getTextEditor(); if (editor != null) { IWorkbenchPartSite site = editor.getSite(); Shell shell = site.getShell(); if (shell != null && !shell.isDisposed()) { return shell; } } return null; } private Display getDisplay() { Shell shell = getShell(); if (shell != null) { return shell.getDisplay(); } return null; } @Override public void setEditor(ITextEditor editor) { super.setEditor(editor); this.textOperationTarget = null; } public static final class XbaseClipboardData { private String sourceIndentifier; private String[] imports; private String[] staticImports; private String[] extensionImports; public XbaseClipboardData(String sourceIndentifier, String[] imports, String[] staticImports, String[] extensionImports) { this.sourceIndentifier = sourceIndentifier; this.imports = imports; this.staticImports = staticImports; this.extensionImports = extensionImports; } public XbaseClipboardData(byte[] bytes) throws IOException { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes)); try { sourceIndentifier = dataIn.readUTF(); imports = readArray(dataIn); staticImports = readArray(dataIn); extensionImports = readArray(dataIn); } finally { dataIn.close(); } } protected final String[] readArray(DataInputStream dataIn) throws IOException { int count = dataIn.readInt(); String[] array = new String[count]; for (int i = 0; i < count; i++) { array[i] = dataIn.readUTF(); } return array; } public byte[] serialize() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); try { dataOut.writeUTF(sourceIndentifier); writeArray(dataOut, imports); writeArray(dataOut, staticImports); writeArray(dataOut, extensionImports); } finally { dataOut.close(); out.close(); } return out.toByteArray(); } protected final void writeArray(DataOutputStream dataOut, String[] array) throws IOException { dataOut.writeInt(array.length); for (int i = 0; i < array.length; i++) { dataOut.writeUTF(array[i]); } } public String getSourceIndentifier() { return sourceIndentifier; } public String[] getImports() { return imports; } public String[] getStaticImports() { return staticImports; } public String[] getExtensionImports() { return extensionImports; } } private static class XbaseClipboardTransfer extends ByteArrayTransfer { private static final String TYPE_NAME = "xbase-source-with-imports-transfer-format"; private static final int TYPEID = registerType(TYPE_NAME); @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object data, TransferData transferData) { if (data instanceof XbaseClipboardData) { try { super.javaToNative(((XbaseClipboardData) data).serialize(), transferData); } catch (IOException e) { //it's best to send nothing if there were problems } } } @Override protected Object nativeToJava(TransferData transferData) { byte[] bytes = (byte[]) super.nativeToJava(transferData); if (bytes != null) { try { return new XbaseClipboardData(bytes); } catch (IOException e) { } } return null; } } } |
blob | t | t | f | blob | 0 | 11212 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xbase.ui/src/org/eclipse/xtext/xbase/ui/editor/actions/ImportsAwareClipboardAction.java/#L79-L520 | 2 | 1534 | 11212 | critical | ||
| 56 | {"response": "YES, I found bad smells", "bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Large class, 5. Long parameter list, 6. Lazy class, 7. Data class, 8. Message chains, 9. Primitive obsession, 10. Shotgun surgery, 11. Feature envy, 12. Long method, 13. Data clumps, 14. Comments, 15. Dead code, 16. Complex conditional, 17. Speculative generality, 18. Inappropriate intimacy, 19. Refused bequest, 20. Switch statements, 21. Temporary field, 22. Volatile data, 23. External duplication, 24. Incomplete library class, 25. Lazy class, 26. Parallel inheritance hierarchies, 27. Large class, 28. Divergent change, 29. Shotgun surgery, 30. Parallel inheritance hierarchies, 31. Lazy class, 32. Data clumps, 33. Inappropriate intimacy, 34. Feature envy, 35. Long method, 36. Data class, 37. Large class, 38. Primitive obsession, 39. Message chains, 40. Long parameter list, 41. Temporary field, 42. Speculative generality, 43. External duplication, 44. Incomplete library class, 45. Comments, 46. Switch statements, 47. Dead code, 48. Complex conditional, 49. Refused bequest, 50. Volatile data." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MapImageLayerTablesSample extends Application { private MapView mapView; private GraphicsOverlay graphicsOverlay; private ServiceFeatureTable commentsTable; private ListView commentsListView; /** * Starting point of this application. * * @param args arguments to this application. */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { // create a stack pane and application scene StackPane stackPane = new StackPane(); Scene scene = new Scene(stackPane); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); // size the stage and add a title stage.setTitle("Map Image Layer Tables Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(scene); stage.show(); // create a map with a basemap ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); // create and add a map image layer to the map // the map image layer contains a feature table with related spatial and non-spatial comment features ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer"); map.getOperationalLayers().add(imageLayer); // create a map view and set the map to it mapView = new MapView(); mapView.setMap(map); // create a graphics overlay to show the related spatial features in graphicsOverlay = new GraphicsOverlay(); mapView.getGraphicsOverlays().add(graphicsOverlay); // show the related graphics as cyan circles SimpleRenderer renderer = new SimpleRenderer(); renderer.setSymbol(new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF00FFFF, 14)); graphicsOverlay.setRenderer(renderer); // create a list view to show the non-spatial comment features commentsListView = new ListView<>(); commentsListView.setMaxSize(200.0, 150.0); // show the comments attribute of the feature in the list commentsListView.setCellFactory(listView -> new ListCell() { @Override protected void updateItem(Feature item, boolean empty) { super.updateItem(item, empty); if (item != null) { ArcGISFeature feature = (ArcGISFeature) item; setText((String) feature.getAttributes().get("comments")); } } }); // when a comment is selected, query its related spatial features and show the first result on the map commentsListView.getSelectionModel().selectedItemProperty().addListener(observable -> showRelatedRequests()); // when the layer is loaded, get the comment features imageLayer.addDoneLoadingListener(() -> { if (imageLayer.getLoadStatus() == LoadStatus.LOADED) { // zoom to the layer's extent mapView.setViewpoint(new Viewpoint(imageLayer.getFullExtent())); // get the comments feature table commentsTable = imageLayer.getTables().get(0); // create query parameters to get features that have non-empty comments QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause("requestid <> '' AND comments <> ''"); // query the comments table for features ListenableFuture featureQuery = commentsTable.queryFeaturesAsync(queryParameters); featureQuery.addDoneListener(() -> { try { // add the returned features to the list view FeatureQueryResult results = featureQuery.get(); for (Feature f : results) { commentsListView.getItems().addAll(f); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Error querying comment features"); } }); } else { new Alert(Alert.AlertType.ERROR, imageLayer.getLoadError().getMessage()).show(); } }); // add the mapview and controls to the stack pane stackPane.getChildren().addAll(mapView, commentsListView); StackPane.setAlignment(commentsListView, Pos.TOP_LEFT); StackPane.setMargin(commentsListView, new Insets(10, 0, 0, 10)); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } /** * Queries for spatial features related to the selected comment in the list view and shows the first result on the * map as a graphic. */ private void showRelatedRequests() { // clear any previous results graphicsOverlay.getGraphics().clear(); // get the selected comment feature from the list view Feature selectedCommentFeature = commentsListView.getSelectionModel().getSelectedItem(); if (selectedCommentFeature != null) { // get the relationships info between layers in the table ArcGISFeature feature = (ArcGISFeature) selectedCommentFeature; List relationshipInfos = commentsTable.getLayerInfo().getRelationshipInfos(); if (!relationshipInfos.isEmpty()) { // use the first relationship for the related query parameters RelationshipInfo commentsRelationshipInfo = relationshipInfos.get(0); RelatedQueryParameters relatedQueryParameters = new RelatedQueryParameters(commentsRelationshipInfo); relatedQueryParameters.setReturnGeometry(true); // query the table for related features using the parameters ListenableFuture> relatedFeaturesRequest = commentsTable .queryRelatedFeaturesAsync(feature, relatedQueryParameters); relatedFeaturesRequest.addDoneListener(() -> { try { // loop through the returned related features List results = relatedFeaturesRequest.get(); if (!results.isEmpty()) { RelatedFeatureQueryResult relatedResult = results.get(0); if (relatedResult.iterator().hasNext()) { // get the first related feature ArcGISFeature relatedFeature = (ArcGISFeature) relatedResult.iterator().next(); // load the feature and get its geometry to show as a graphic on the map relatedFeature.loadAsync(); relatedFeature.addDoneLoadingListener(() -> { if (relatedFeature.getLoadStatus() == LoadStatus.LOADED) { Point point = (Point) relatedFeature.getGeometry(); Graphic graphic = new Graphic(point); graphicsOverlay.getGraphics().add(graphic); // zoom to the graphic mapView.setViewpointCenterAsync(point, 40000); } }); } } else { new Alert(Alert.AlertType.INFORMATION, "No related features found").show(); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Failed to query relationships").show(); } }); } } } @Override public void stop() { // releases resources when the application closes if (mapView != null) { mapView.dispose(); } } } |
blob | f | f | f | blob | 0 | 976 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/imagelayers/map_image_layer_tables/MapImageLayerTablesSample.java/#L53-L234 | 2 | 56 | 976 | major | ||
| 1487 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 11103 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 | 2 | 1487 | 11103 | minor |
| 2524 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication within constructor 4. Null check in constructor 5. Inefficient searching method in getProperty() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | Long method2 Feature envy3 Code duplication within constructor4 Null check in constructor5 Inefficient searching method in getProperty() | t | f | f | . Long method2. Feature envy3. Code duplication within constructor4. Null check in constructor5. Inefficient searching method in getProperty() | data class | 0 | 14719 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 2 | 2524 | 14719 | minor |
| 2313 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14103 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 2 | 2313 | 14103 | minor |
| 3573 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7856 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 3573 | 7856 | minor | ||
| 1413 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession 3. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Primitive obsession3 Shotgun surgery | t | f | f | . Long method2. Primitive obsession3. Shotgun surgery | data class | 0 | 10905 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1413 | 10905 | major |
| 656 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6405 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 2 | 656 | 6405 | critical |
| 1689 | {"output":"YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MapImageLayerTablesSample extends Application { private MapView mapView; private GraphicsOverlay graphicsOverlay; private ServiceFeatureTable commentsTable; private ListView commentsListView; /** * Starting point of this application. * * @param args arguments to this application. */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { // create a stack pane and application scene StackPane stackPane = new StackPane(); Scene scene = new Scene(stackPane); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); // size the stage and add a title stage.setTitle("Map Image Layer Tables Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(scene); stage.show(); // create a map with a basemap ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); // create and add a map image layer to the map // the map image layer contains a feature table with related spatial and non-spatial comment features ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer"); map.getOperationalLayers().add(imageLayer); // create a map view and set the map to it mapView = new MapView(); mapView.setMap(map); // create a graphics overlay to show the related spatial features in graphicsOverlay = new GraphicsOverlay(); mapView.getGraphicsOverlays().add(graphicsOverlay); // show the related graphics as cyan circles SimpleRenderer renderer = new SimpleRenderer(); renderer.setSymbol(new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF00FFFF, 14)); graphicsOverlay.setRenderer(renderer); // create a list view to show the non-spatial comment features commentsListView = new ListView<>(); commentsListView.setMaxSize(200.0, 150.0); // show the comments attribute of the feature in the list commentsListView.setCellFactory(listView -> new ListCell() { @Override protected void updateItem(Feature item, boolean empty) { super.updateItem(item, empty); if (item != null) { ArcGISFeature feature = (ArcGISFeature) item; setText((String) feature.getAttributes().get("comments")); } } }); // when a comment is selected, query its related spatial features and show the first result on the map commentsListView.getSelectionModel().selectedItemProperty().addListener(observable -> showRelatedRequests()); // when the layer is loaded, get the comment features imageLayer.addDoneLoadingListener(() -> { if (imageLayer.getLoadStatus() == LoadStatus.LOADED) { // zoom to the layer's extent mapView.setViewpoint(new Viewpoint(imageLayer.getFullExtent())); // get the comments feature table commentsTable = imageLayer.getTables().get(0); // create query parameters to get features that have non-empty comments QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause("requestid <> '' AND comments <> ''"); // query the comments table for features ListenableFuture featureQuery = commentsTable.queryFeaturesAsync(queryParameters); featureQuery.addDoneListener(() -> { try { // add the returned features to the list view FeatureQueryResult results = featureQuery.get(); for (Feature f : results) { commentsListView.getItems().addAll(f); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Error querying comment features"); } }); } else { new Alert(Alert.AlertType.ERROR, imageLayer.getLoadError().getMessage()).show(); } }); // add the mapview and controls to the stack pane stackPane.getChildren().addAll(mapView, commentsListView); StackPane.setAlignment(commentsListView, Pos.TOP_LEFT); StackPane.setMargin(commentsListView, new Insets(10, 0, 0, 10)); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } /** * Queries for spatial features related to the selected comment in the list view and shows the first result on the * map as a graphic. */ private void showRelatedRequests() { // clear any previous results graphicsOverlay.getGraphics().clear(); // get the selected comment feature from the list view Feature selectedCommentFeature = commentsListView.getSelectionModel().getSelectedItem(); if (selectedCommentFeature != null) { // get the relationships info between layers in the table ArcGISFeature feature = (ArcGISFeature) selectedCommentFeature; List relationshipInfos = commentsTable.getLayerInfo().getRelationshipInfos(); if (!relationshipInfos.isEmpty()) { // use the first relationship for the related query parameters RelationshipInfo commentsRelationshipInfo = relationshipInfos.get(0); RelatedQueryParameters relatedQueryParameters = new RelatedQueryParameters(commentsRelationshipInfo); relatedQueryParameters.setReturnGeometry(true); // query the table for related features using the parameters ListenableFuture> relatedFeaturesRequest = commentsTable .queryRelatedFeaturesAsync(feature, relatedQueryParameters); relatedFeaturesRequest.addDoneListener(() -> { try { // loop through the returned related features List results = relatedFeaturesRequest.get(); if (!results.isEmpty()) { RelatedFeatureQueryResult relatedResult = results.get(0); if (relatedResult.iterator().hasNext()) { // get the first related feature ArcGISFeature relatedFeature = (ArcGISFeature) relatedResult.iterator().next(); // load the feature and get its geometry to show as a graphic on the map relatedFeature.loadAsync(); relatedFeature.addDoneLoadingListener(() -> { if (relatedFeature.getLoadStatus() == LoadStatus.LOADED) { Point point = (Point) relatedFeature.getGeometry(); Graphic graphic = new Graphic(point); graphicsOverlay.getGraphics().add(graphic); // zoom to the graphic mapView.setViewpointCenterAsync(point, 40000); } }); } } else { new Alert(Alert.AlertType.INFORMATION, "No related features found").show(); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Failed to query relationships").show(); } }); } } } @Override public void stop() { // releases resources when the application closes if (mapView != null) { mapView.dispose(); } } } |
blob | t | f | f | blob | 0 | 11694 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/imagelayers/map_image_layer_tables/MapImageLayerTablesSample.java/#L53-L234 | 1 | 1689 | 11694 | major | ||
| 1889 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12304 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 | 2 | 1889 | 12304 | minor |
| 742 | {"message":"YES I found bad smells","bad_smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
blob | long method | t | t | f | long method | blob | 0 | 6976 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 742 | 6976 | major |
| 428 | YES I found bad smells It is difficult to accurately comment on the code without understanding its context and intended purpose. However, here are some potential bad smells that could be present in the code: 1. Long method in equals() method 2. Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own data. Note: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data. However, this could be necessary for the class's intended purpose. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method in equals() method2 Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own dataNote: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data However, this could be necessary for the class's intended purpose | t | f | f | . Long method in equals() method2. Feature envy in hashCode() and equals() methods, as they are accessing data from a different object (the AvroWrapper instance) rather than their own data.Note: The toString() method is also potentially a feature envy, as it is accessing data from the AvroWrapper instance rather than its own data. However, this could be necessary for the class's intended purpose. | data class | 0 | 4270 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 428 | 4270 | major |
| 1214 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10314 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1214 | 10314 | minor |
| 2114 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 13192 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 2114 | 13192 | major |
| 5396 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Not specified | f | f | f | false | 0 | 15166 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 5396 | 15166 | minor | |
| 5760 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | f | f | f | feature envy | 0 | 14516 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5760 | 14516 | minor | ||
| 2495 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14640 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 2495 | 14640 | minor |
| 688 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6634 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 2 | 688 | 6634 | major |
| 1776 | {"message": "YES I found bad smells the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11956 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 1776 | 11956 | major |
| 2239 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13618 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 1 | 2239 | 13618 | minor |
| 2626 | YES I found bad smells the bad smells are: 1. Magic number literal used for generation strategy. 2. Lack of abstraction for repeating code in constructor. 3. String concatenation used in toString() method instead of StringBuilder. 4. Excessive commenting. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Magic number literal used for generation strategy2 Lack of abstraction for repeating code in constructor3 String concatenation used in toString() method instead of StringBuilder4 Excessive commenting | t | f | f | . Magic number literal used for generation strategy.2. Lack of abstraction for repeating code in constructor.3. String concatenation used in toString() method instead of StringBuilder.4. Excessive commenting. | data class | 0 | 15080 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 2 | 2626 | 15080 | minor |
| 946 | * @return the set of aggregated modules NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | f | f | f | feature envy | 0 | 8494 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 2 | 946 | 8494 | major | ||
| 1965 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12591 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 1965 | 12591 | major |
| 816 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inappropriate delegation 5. Unused parameters 6. Method chaining 7. Violation of Single Responsibility Principle (SRP) as the class has multiple responsibilities and is not focused on a single task. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class WSDLReaderImpl extends com.ibm.wsdl.xml.WSDLReaderImpl { private WSDLFactory _localFactory; WSDLReaderImpl(WSDLFactory factory) { _localFactory = factory; } @Override protected WSDLFactory getWSDLFactory() throws WSDLException { return _localFactory; } @Override public Binding parseBinding(Element bindingEl, Definition def) throws WSDLException { Binding binding = super.parseBinding(bindingEl, def); binding.setDocumentationElement(null); return binding; } @Override public BindingFault parseBindingFault(Element bindingFaultEl, Definition def) throws WSDLException { BindingFault bindingFault = super.parseBindingFault(bindingFaultEl, def); bindingFault.setDocumentationElement(null); return bindingFault; } @Override public BindingInput parseBindingInput(Element bindingInputEl, Definition def) throws WSDLException { BindingInput bindingInput = super.parseBindingInput(bindingInputEl, def); bindingInput.setDocumentationElement(null); return bindingInput; } @Override public BindingOperation parseBindingOperation(Element bindingOperationEl, PortType portType, Definition def) throws WSDLException { BindingOperation bindingOperation = super.parseBindingOperation(bindingOperationEl, portType, def); bindingOperation.setDocumentationElement(null); return bindingOperation; } @Override public BindingOutput parseBindingOutput(Element bindingOutputEl, Definition def) throws WSDLException { BindingOutput BindingOutput = super.parseBindingOutput(bindingOutputEl, def); BindingOutput.setDocumentationElement(null); return BindingOutput; } @SuppressWarnings("rawtypes") @Override public Definition parseDefinitions(String documentBaseURI, Element defEl, Map importedDefs) throws WSDLException { Definition definition = super.parseDefinitions(documentBaseURI, defEl, importedDefs); definition.setDocumentationElement(null); return definition; } @Override public Fault parseFault(Element faultEl, Definition def) throws WSDLException { Fault fault = super.parseFault(faultEl, def); fault.setDocumentationElement(null); return fault; } @Override public Input parseInput(Element inputEl, Definition def) throws WSDLException { Input input = super.parseInput(inputEl, def); input.setDocumentationElement(null); return input; } @Override public Message parseMessage(Element msgEl, Definition def) throws WSDLException { Message message = super.parseMessage(msgEl, def); message.setDocumentationElement(null); return message; } @Override public Operation parseOperation(Element opEl, PortType portType, Definition def) throws WSDLException { Operation operation = super.parseOperation(opEl, portType, def); operation.setDocumentationElement(null); return operation; } @Override public Output parseOutput(Element outputEl, Definition def) throws WSDLException { Output output = super.parseOutput(outputEl, def); output.setDocumentationElement(null); return output; } @Override public Part parsePart(Element partEl, Definition def) throws WSDLException { Part part = super.parsePart(partEl, def); part.setDocumentationElement(null); return part; } @Override public Port parsePort(Element portEl, Definition def) throws WSDLException { Port Port = super.parsePort(portEl, def); Port.setDocumentationElement(null); return Port; } @Override public PortType parsePortType(Element portTypeEl, Definition def) throws WSDLException { PortType portType = super.parsePortType(portTypeEl, def); portType.setDocumentationElement(null); return portType; } @Override public Service parseService(Element serviceEl, Definition def) throws WSDLException { Service service = super.parseService(serviceEl, def); service.setDocumentationElement(null); return service; } @Override public Types parseTypes(Element typesEl, Definition def) throws WSDLException { Types types = super.parseTypes(typesEl, def); types.setDocumentationElement(null); return types; } } |
blob | Long method2 Feature envy3 Duplicate code4 Inappropriate delegation5 Unused parameters6 Method chaining7 Violation of Single Responsibility Principle (SRP) as the class has multiple responsibilities and is not focused on a single task | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inappropriate delegation5. Unused parameters6. Method chaining7. Violation of Single Responsibility Principle (SRP) as the class has multiple responsibilities and is not focused on a single task. | blob | 0 | 7667 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/wsdl/WSDLReaderImpl.java/#L52-L177 | 2 | 816 | 7667 | major |
| 1245 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10419 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1245 | 10419 | critical |
| 1203 | { "response": "YES I found bad smells", "detected_bad_smells": [ 1.29, 2.27 ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | 1.29, 2.27 | t | t | f | 1.29, 2.27 | data class | 0 | 10286 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 1 | 1203 | 10286 | major |
| 712 | ; YES I found bad smells The bad smells are: 1. Long method 2. Feature envy: method isAuthorized() 3. Feature envy: method getMessageConverters() 4. Primitive obsession: multiple variable declarations and assignments for message converters 5. Data clumps: multiple variables related to HTTP message converters 6. Message chain: multiple method calls on restTemplate and converter objects 7. Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data 8. Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters() 9. Data clumps: multiple variables related to access tokens and token strategies 10. Shotgun surgery: any changes to methods or constructors could require changing multiple methods/classes. 11. Lazy class: method postConstructionConfiguration() does not have a default behavior and is not used in the class. 12. Long parameter list: constructor for method createRestTemplate() has multiple parameters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } } |
blob | Long method2 Feature envy: method isAuthorized()3 Feature envy: method getMessageConverters()4 Primitive obsession: multiple variable declarations and assignments for message converters5 Data clumps: multiple variables related to HTTP message converters6 Message chain: multiple method calls on restTemplate and converter objects7 Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data8 Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters()9 Data clumps: multiple variables related to access tokens and token strategies | t | f | f | . Long method2. Feature envy: method isAuthorized()3. Feature envy: method getMessageConverters()4. Primitive obsession: multiple variable declarations and assignments for message converters5. Data clumps: multiple variables related to HTTP message converters6. Message chain: multiple method calls on restTemplate and converter objects7. Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data8. Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters()9. Data clumps: multiple variables related to access tokens and token strategies | blob | 0 | 6781 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 | 2 | 712 | 6781 | minor |
| 669 | NO, I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 6552 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 2 | 669 | 6552 | minor | ||
| 1570 | {"response": "YES I found bad smells", "bad smells are:": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | long method | t | t | f | long method | data class | 0 | 11335 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 1570 | 11335 | major |
| 2043 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12862 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 | 2 | 2043 | 12862 | minor |
| 4068 | { "output": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10741 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 4068 | 10741 | minor |
| 2676 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15238 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 2676 | 15238 | minor |
| 1560 | YES, found bad smells: 1. Long method 2. Feature envy 3. Duplicate code/ Duplicate functionality 4. Indecent exposure/ Unnecessary getter and setter methods 5. Bad encapsulation/ Data clump 6. Switch-statements (in toMapping() method) 7. Excessive use of null checks 8. Hardcoded values/ Magic numbers 9. Complex conditionals/ Nesting of conditionals 10. Inconsistent naming conventions (e.g. mapAddress() vs addAddressMapping()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | Long method2 Feature envy3 Duplicate code/ Duplicate functionality4 Indecent exposure/ Unnecessary getter and setter methods5 Bad encapsulation/ Data clump6 Switch-statements (in toMapping() method)7 Excessive use of null checks8 Hardcoded values/ Magic numbers9 Complex conditionals/ Nesting of conditionals | t | f | f | . Long method2. Feature envy3. Duplicate code/ Duplicate functionality4. Indecent exposure/ Unnecessary getter and setter methods5. Bad encapsulation/ Data clump6. Switch-statements (in toMapping() method)7. Excessive use of null checks8. Hardcoded values/ Magic numbers9. Complex conditionals/ Nesting of conditionals | blob | 0 | 11305 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 2 | 1560 | 11305 | major |
| 1456 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 11010 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 2 | 1456 | 11010 | critical |
| 3933 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10289 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 3933 | 10289 | major |
| 2114 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13192 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 2114 | 13192 | major |
| 2082 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Parameter laziness | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AppService implements ApplicationService { private static final Logger logger = LoggerFactory.getLogger(ApplicationService.class); /** * Create an register an application service using the default alias {@link ApplicationService#ALIAS}. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @return Application service instance. */ public static ApplicationService createAndRegister(TopologyProvider provider, DirectSubmitter submitter) { AppService service = new AppService(provider, submitter, ALIAS); submitter.getServices().addService(ApplicationService.class, service); return service; } private final Map> applications = Collections.synchronizedMap(new HashMap<>()); private final TopologyProvider provider; private final DirectSubmitter submitter; /** * Create an {@code ApplicationService} instance. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @param alias Alias used to register the control MBean. */ public AppService(TopologyProvider provider, DirectSubmitter submitter, String alias) { this.provider = provider; this.submitter = submitter; ControlService cs = submitter.getServices().getService(ControlService.class); if (cs != null) cs.registerControl(ApplicationServiceMXBean.TYPE, ALIAS+System.currentTimeMillis(), alias, ApplicationServiceMXBean.class, new AppServiceControl(this)); } @Override public void registerTopology(String applicationName, BiConsumer builder) { if (applicationName == null || applicationName.isEmpty()) { throw new IllegalArgumentException(); } logger.trace("Register application name: {}", applicationName); applications.put(applicationName, builder); } /** * Create a new class loader for the jar and register any * topology application that is registered as a service provider. */ @Override public void registerJar(String jarURL, String jsonConfig) throws Exception { logger.trace("Register jar: {}", jarURL); // If it's a http URL download it otherwise use directly. URL url = new URL(jarURL); String protocol = url.getProtocol(); if ("http".equals(protocol) || "https".equals(protocol)) { url = downloadJar(url); } URLClassLoader loader = new URLClassLoader(new URL[] {url}); for (TopologyBuilder topoBuilder : ServiceLoader.load(TopologyBuilder.class, loader)) { registerTopology(topoBuilder.getName(), topoBuilder.getBuilder()); } } /** * Download an HTTP URL to a local file. * @param url URL to download from. * @return URL of the local file. */ private URL downloadJar(URL url) throws Exception { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Error response code for URL: {} : response code={}", url.toExternalForm(), responseCode); throw new IOException(); } String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); if (disposition != null) { // extracts file name from header field int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name from URL path String path = url.getPath(); if (!path.isEmpty()) { int lastSlash = path.lastIndexOf("/"); if (lastSlash == -1) fileName = path; else fileName = path.substring(lastSlash+1); } } // TODO - allow persistence across reboots // For now just store in a temp directory Path dir = Files.createTempDirectory("edgentjars"); File file; if (fileName.isEmpty()) file = File.createTempFile("edgent", "jar", dir.toFile()); else file = new File(dir.toFile(), fileName); InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); logger.trace("Register jar downloaded as: {}", file); return file.toURI().toURL(); } @Override public Set getApplicationNames() { synchronized (applications) { return new HashSet<>(applications.keySet()); } } BiConsumer getBuilder(String applicationName) { return applications.get(applicationName); } TopologyProvider getProvider() { return provider; } DirectSubmitter getSubmitter() { return submitter; } } |
blob | Long method2 Feature envy3 Parameter laziness | t | f | f | . Long method2. Feature envy3. Parameter laziness | blob | 0 | 13073 | https://github.com/apache/incubator-edgent/blob/2e44089358175964650fed5e2bf4ad071b05b7d6/runtime/appservice/src/main/java/org/apache/edgent/runtime/appservice/AppService.java/#L62-L217 | 2 | 2082 | 13073 | minor |
| 2171 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | blob | t | t | f | blob | data class | 0 | 13382 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 1 | 2171 | 13382 | major |
| 1799 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12009 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1799 | 12009 | minor |
| 890 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8082 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 890 | 8082 | minor |
| 2511 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Deprecated methods 5. Redundant comments 6. Poor code organization (lack of clear structure or grouping of methods and variables) 7. Mixed use of tabs and spaces for indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Long method2 Feature envy3 Commented out code4 Deprecated methods5 Redundant comments6 Poor code organization (lack of clear structure or grouping of methods and variables)7 Mixed use of tabs and spaces for indentation | t | f | f | . Long method2. Feature envy3. Commented out code4. Deprecated methods5. Redundant comments6. Poor code organization (lack of clear structure or grouping of methods and variables)7. Mixed use of tabs and spaces for indentation | data class | 0 | 14687 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 2511 | 14687 | major |
| 2437 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14471 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 | 2 | 2437 | 14471 | major |
| 1522 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11174 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 1522 | 11174 | minor |
| 699 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else if ( (LA12_0=='\'') ) {s = 10;} else if ( (LA12_0=='/') ) {s = 11;} else if ( ((LA12_0>='\t' && LA12_0<='\n')||LA12_0=='\r'||LA12_0==' ') ) {s = 12;} else if ( ((LA12_0>='\u0000' && LA12_0<='\b')||(LA12_0>='\u000B' && LA12_0<='\f')||(LA12_0>='\u000E' && LA12_0<='\u001F')||LA12_0=='!'||(LA12_0>='#' && LA12_0<='&')||(LA12_0>='(' && LA12_0<='.')||(LA12_0>=':' && LA12_0<='@')||(LA12_0>='[' && LA12_0<=']')||LA12_0=='`'||(LA12_0>='{' && LA12_0<='\uFFFF')) ) {s = 13;} if ( s>=0 ) return s; break; case 1 : int LA12_9 = input.LA(1); s = -1; if ( ((LA12_9>='\u0000' && LA12_9<='\uFFFF')) ) {s = 22;} else s = 13; if ( s>=0 ) return s; break; case 2 : int LA12_10 = input.LA(1); s = -1; if ( ((LA12_10>='\u0000' && LA12_10<='\uFFFF')) ) {s = 22;} else s = 13; if ( s>=0 ) return s; break; } NoViableAltException nvae = new NoViableAltException(getDescription(), 12, _s, input); error(nvae); throw nvae; } } } |
blob | long method | t | t | f | long method | blob | 0 | 6685 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.core.idea.tests/src-gen/org/eclipse/xtext/parser/assignments/idea/parser/antlr/internal/PsiInternalAssignmentsTestLanguageLexer.java/#L1126-L1204 | 1 | 699 | 6685 | minor |
| 1470 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11048 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 | 1 | 1470 | 11048 | minor |
| 2238 | { "response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 13615 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 1 | 2238 | 13615 | minor |
| 1474 | {"message": "YES I found bad smells\n1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Not specified | f | f | f | false | 0 | 11056 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 1474 | 11056 | minor | |
| 2190 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 13458 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 1 | 2190 | 13458 | minor |
| 1728 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | f | f | f | feature envy | 0 | 11811 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 1728 | 11811 | minor | ||
| 3766 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void generateReport( Locale locale, LinkcheckModel linkcheckModel ) { LinkcheckReportGenerator reportGenerator = new LinkcheckReportGenerator( i18n ); reportGenerator.setExcludedHttpStatusErrors( excludedHttpStatusErrors ); reportGenerator.setExcludedHttpStatusWarnings( excludedHttpStatusWarnings ); reportGenerator.setExcludedLinks( excludedLinks ); reportGenerator.setExcludedPages( excludedPages ); reportGenerator.setHttpFollowRedirect( httpFollowRedirect ); reportGenerator.setHttpMethod( httpMethod ); reportGenerator.setOffline( offline ); reportGenerator.generateReport( locale, linkcheckModel, getSink() ); closeReport(); // Copy the images copyStaticResources(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9426 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-linkcheck-plugin/src/main/java/org/apache/maven/plugins/linkcheck/LinkcheckReport.java/#L448-L465 | 1 | 3766 | 9426 | minor |
| 1557 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | Long Method, Feature Envy | t | f | f | Long Method, Feature Envy | blob | 0 | 11288 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 1 | 1557 | 11288 | major |
| 2897 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2135 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L33809-L33879 | 2 | 2897 | 2135 | minor | ||
| 2165 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2165 | 13347 | major |
| 1835 | YES I found bad smells The bad smells are: 1. Long method 2. Type Checking 3. Temporal coupling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
feature envy | Long method2 Type Checking3 Temporal coupling | t | f | f | . Long method2. Type Checking3. Temporal coupling | feature envy | 0 | 12133 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 1835 | 12133 | minor |
| 4237 | YES I found bad smells the bad smells are: 1. Duplicate code (in both constructors) 2. Long method (for Subchannel() constructor and setPitch() method) 3. Feature envy (copy() method accessing fields from another class) 4. Primitive obsession (using primitive data types instead of objects) 5. Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | Duplicate code (in both constructors)2 Long method (for Subchannel() constructor and setPitch() method)3 Feature envy (copy() method accessing fields from another class)4 Primitive obsession (using primitive data types instead of objects)5 Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | t | f | f | . Duplicate code (in both constructors)2. Long method (for Subchannel() constructor and setPitch() method)3. Feature envy (copy() method accessing fields from another class)4. Primitive obsession (using primitive data types instead of objects)5. Misplaced method (equals(), clone(), copy(), and hashCode() methods should not be in Subchannel class but in a separate class for handling comparisons and cloning) | data class | 0 | 11155 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 4237 | 11155 | minor |
| 396 | YES I found bad smells the bad smells are: 1. Unused constructor 2. Poorly named variables (e.g. Tuple, Mapping) 3. Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Unused constructor2 Poorly named variables (eg Tuple, Mapping)3 Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | t | f | f | . Unused constructor2. Poorly named variables (e.g. Tuple, Mapping)3. Potential Feature Envy (accessing tuple and mapping properties outside of the Cause class) | data class | 0 | 4035 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 396 | 4035 | major |
| 2354 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14226 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 2 | 2354 | 14226 | major |
| 607 | YES I found bad smells: 1. Long method 2. Feature envy 3. Duplicate code 4. Violation of Single Responsibility principle 5. Lack of encapsulation 6. Use of raw types 7. Use of primitive types instead of objects 8. Lack of comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method 2 Feature envy 3 Duplicate code 4 Violation of Single Responsibility principle 5 Lack of encapsulation 6 Use of raw types 7 Use of primitive types instead of objects 8 Lack of comments/documentation | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Violation of Single Responsibility principle 5. Lack of encapsulation 6. Use of raw types 7. Use of primitive types instead of objects 8. Lack of comments/documentation. | data class | 0 | 6104 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 607 | 6104 | major |
| 1556 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public abstract class AbstractEntitiesRuntimeModule extends DefaultXbaseRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/xtext/idea/example/entities/Entities.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.idea.example.entities.Entities"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("entities"); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class bindIGrammarAccess() { return EntitiesGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISemanticSequencer() { return EntitiesSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISyntacticSequencer() { return EntitiesSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIParser() { return EntitiesParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIAntlrTokenFileProvider() { return EntitiesAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindLexer() { return InternalEntitiesLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider provideInternalEntitiesLexer() { return LexerProvider.create(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class bindEntitiesValidator() { return EntitiesValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public Class bindIBatchScopeProvider() { return EntitiesScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIScopeProviderDelegate(Binder binder) { binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(XImportSectionNamespaceScopeProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIgnoreCaseLinking(Binder binder) { binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIContainer$Manager() { return StateBasedContainerManager.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIAllContainersState$Provider() { return ResourceSetBasedAllContainersStateProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptions(Binder binder) { binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptionsPersisted(Binder binder) { binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class bindIFormatter2() { return EntitiesFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIQualifiedNameProvider() { return XbaseQualifiedNameProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindILocationInFileProvider() { return JvmLocationInFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIGlobalScopeProvider() { return TypesAwareDefaultGlobalScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindFeatureNameValidator() { return LogicalContainerAwareFeatureNameValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultBatchTypeResolver() { return LogicalContainerAwareBatchTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultReentrantTypeResolver() { return LogicalContainerAwareReentrantTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIResourceValidator() { return DerivedStateAwareResourceValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIJvmModelInferrer() { return EntitiesJvmModelInferrer.class; } } |
blob | t | f | f | blob | 0 | 11283 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities/src-gen/org/eclipse/xtext/idea/example/entities/AbstractEntitiesRuntimeModule.java/#L76-L249 | 1 | 1556 | 11283 | minor | ||
| 1218 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10324 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1218 | 10324 | major |
| 434 | YES I found bad smells the bad smells are: 1. long method (isSatisfied), 2. feature envy (getVarsMentioned, applyNodeTransform, copySubstitute, addAll, add, getListRaw, prepareExprs, equals), 3. data clump (expressions), 4. repeating code (in emptyList and in various constructors), 5. primitive obsession (size, isEmpty), 6. magic numbers/strings (# in hashCode, "right" in equals), 7. confusing names (execCxt? x? bySyntax?), 8. unused import (Context), 9. commented out code, 10. missing override annotation (equals with one parameter), 11. lack of encapsulation (public access to expressions list), 12. violation of Single Responsibility Principle (contains various functionalities unrelated to the ExprList class, such as setting up expressions or splitting conjunctions), 13. missing validation (possible NullPointer exception in equals method if exprs or expr is null). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | long method (isSatisfied), 2 feature envy (getVarsMentioned, applyNodeTransform, copySubstitute, addAll, add, getListRaw, prepareExprs, equals), 3 data clump (expressions), 4 repeating code (in emptyList and in various constructors), 5 primitive obsession (size, isEmpty), 6 magic numbers/strings (# in hashCode, "right" in equals), 7 confusing names (execCxt? x? bySyntax?), 8 unused import (Context), 9 commented out code, | t | f | f | . long method (isSatisfied), 2. feature envy (getVarsMentioned, applyNodeTransform, copySubstitute, addAll, add, getListRaw, prepareExprs, equals), 3. data clump (expressions), 4. repeating code (in emptyList and in various constructors), 5. primitive obsession (size, isEmpty), 6. magic numbers/strings (# in hashCode, "right" in equals), 7. confusing names (execCxt? x? bySyntax?), 8. unused import (Context), 9. commented out code, | blob | 0 | 4283 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 2 | 434 | 4283 | major |
| 4577 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12170 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 1 | 4577 | 12170 | major |
| 90 | {"response": "YES, I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class TestConfiguration { private String downloadUrl; private final String description; private TestSuite suite; public TestConfiguration(String description) { this.description = description; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getDescription() { return description; } @Override public String toString() { return getClass().getSimpleName() + " [" + description + "]"; } public TestSuite createSuite(TestSuite parentSuite) { suite = new TestSuite("Testing on " + getDescription()); parentSuite.addTest(suite); suite.addTest(new Activation("TestSuite: " + getDescription(), true)); return suite; } public void add(Class clazz) { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTestSuite(clazz); } public void done() { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTest(new Activation("done", false)); suite = null; } private final class Activation extends TestCase { private final boolean activate; private Activation(String name, boolean activate) { super(name); this.activate = activate; } @Override protected void runTest() throws Throwable { if (activate) { activate(); } else { getDefault().activate(); } } } protected abstract TestConfiguration getDefault(); public abstract void activate(); public abstract TestHarness createHarness(); } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 1240 | https://github.com/spring-projects/eclipse-integration-tcserver/blob/5b381256cb35cfe2aa21f5093558f7ca927c289f/com.vmware.vfabric.ide.eclipse.tcserver.tests/src/com/vmware/vfabric/ide/eclipse/tcserver/tests/support/TestConfiguration.java/#L21-L95 | 1 | 90 | 1240 | major |
| 1399 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10858 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 1399 | 10858 | major |
| 2284 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13857 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 2284 | 13857 | major |
| 7 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 573 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 1 | 7 | 573 | minor |
| 913 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Bug288734TestLanguageSwitch extends Switch { /** * The cached model package * * * @generated */ protected static Bug288734TestLanguagePackage modelPackage; /** * Creates an instance of the switch. * * * @generated */ public Bug288734TestLanguageSwitch() { if (modelPackage == null) { modelPackage = Bug288734TestLanguagePackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * * * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls caseXXX for each class of the model until one returns a non null result; it yields that result. * * * @return the first non-null result returned by a caseXXX call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case Bug288734TestLanguagePackage.MODEL: { Model model = (Model)theEObject; T result = caseModel(model); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TCONSTANT: { TConstant tConstant = (TConstant)theEObject; T result = caseTConstant(tConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TSTRING_CONSTANT: { TStringConstant tStringConstant = (TStringConstant)theEObject; T result = caseTStringConstant(tStringConstant); if (result == null) result = caseTConstant(tStringConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TINTEGER_CONSTANT: { TIntegerConstant tIntegerConstant = (TIntegerConstant)theEObject; T result = caseTIntegerConstant(tIntegerConstant); if (result == null) result = caseTConstant(tIntegerConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TBOOLEAN_CONSTANT: { TBooleanConstant tBooleanConstant = (TBooleanConstant)theEObject; T result = caseTBooleanConstant(tBooleanConstant); if (result == null) result = caseTConstant(tBooleanConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TANNOTATION: { TAnnotation tAnnotation = (TAnnotation)theEObject; T result = caseTAnnotation(tAnnotation); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of 'Model'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'Model'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseModel(Model object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TConstant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TConstant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTConstant(TConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TString Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TString Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTStringConstant(TStringConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TInteger Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TInteger Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTIntegerConstant(TIntegerConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TBoolean Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TBoolean Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTBooleanConstant(TBooleanConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TAnnotation'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TAnnotation'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTAnnotation(TAnnotation object) { return null; } /** * Returns the result of interpreting the object as an instance of 'EObject'. * * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'EObject'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //Bug288734TestLanguageSwitch |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8243 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug288734TestLanguage/util/Bug288734TestLanguageSwitch.java/#L26-L238 | 2 | 913 | 8243 | major |
| 4928 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
data class | f | f | f | data class | 0 | 13480 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 1 | 4928 | 13480 | minor | ||
| 1717 | {"message": "YES I found bad smells", "bad smells are": [ "Long Method" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 11784 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 1717 | 11784 | minor |
| 260 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | long method | t | t | f | long method | blob | 0 | 2825 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 1 | 260 | 2825 | minor |
| 2654 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 15180 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 2654 | 15180 | minor |
| 1775 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class Prefixes { /** * The SI “deca” prefix. This is the only SI prefix encoded on two letters instead than one. * It can be represented by the CJK compatibility character “㍲”, but use of those characters * is generally not recommended outside of Chinese, Japanese or Korean texts. */ private static final String DECA = "da"; /** * The SI prefixes in increasing order. The only two-letters prefix – “da” – is encoded using the JCK compatibility * character “㍲”. The Greek letter μ is repeated twice: the U+00B5 character for micro sign (this is the character * that Apache SIS uses in unit symbols) and the U+03BC character for the Greek small letter “mu” (the later is the * character that appears when decomposing JCK compatibility characters with {@link java.text.Normalizer}). * Both characters have same appearance but different values. * * For each prefix at index i, the multiplication factor is given by 10 raised to power {@code POWERS[i]}. */ private static final char[] PREFIXES = {'E','G','M','P','T','Y','Z','a','c','d','f','h','k','m','n','p','y','z','µ','μ','㍲'}; private static final byte[] POWERS = {18, 9, 6, 15, 12, 24, 21,-18, -2, -1,-15, 2, 3, -3, -9,-12,-24,-21, -6, -6, 1}; /** * The SI prefixes from smallest to largest. Power of tens go from -24 to +24 inclusive with a step of 3, * except for the addition of -2, -1, +1, +2 and the omission of 0. * * @see #symbol(double, int) */ private static final char[] ENUM = {'y','z','a','f','p','n','µ','m','c','d','㍲','h','k','M','G','T','P','E','Z','Y'}; /** * The maximal power of 1000 for the prefixes in the {@link #ENUM} array. Note that 1000⁸ = 1E+24. */ static final int MAX_POWER = 8; /** * The converters for SI prefixes, created when first needed. * * @see #converter(char) */ private static final LinearConverter[] CONVERTERS = new LinearConverter[POWERS.length]; /** * Do not allow instantiation of this class. */ private Prefixes() { } /** * Returns the converter for the given SI prefix, or {@code null} if none. * Those converters are created when first needed and cached for reuse. */ static LinearConverter converter(final char prefix) { final int i = Arrays.binarySearch(PREFIXES, prefix); if (i < 0) { return null; } synchronized (CONVERTERS) { LinearConverter c = CONVERTERS[i]; if (c == null) { final int p = POWERS[i]; final double numerator, denominator; if (p >= 0) { numerator = MathFunctions.pow10(p); denominator = 1; } else { numerator = 1; denominator = MathFunctions.pow10(-p); } c = LinearConverter.scale(numerator, denominator); CONVERTERS[i] = c; } return c; } } /** * Returns the SI prefix symbol for the given scale factor, or 0 if none. * * @param scale the scale factor. * @param power the unit power. For example if we are scaling m², then this is 2. * @return the prefix, or 0 if none. */ static char symbol(double scale, final int power) { switch (power) { case 0: return 0; case 1: break; case 2: scale = Math.sqrt(scale); break; case 3: scale = Math.cbrt(scale); break; default: scale = Math.pow(scale, 1.0/power); } final int n = Numerics.toExp10(Math.getExponent(scale)) + 1; if (AbstractConverter.epsilonEquals(MathFunctions.pow10(n), scale)) { int i = Math.abs(n); switch (i) { case 0: return 0; case 1: // Fallthrough case 2: break; default: { if (i > (MAX_POWER*3) || (i % 3) != 0) { return 0; } i = i/3 + 2; break; } } return ENUM[n >= 0 ? (MAX_POWER+1) + i : (MAX_POWER+2) - i]; } return 0; } /** * Returns the concatenation of the given prefix with the given unit symbol. */ static String concat(final char prefix, final String unit) { return (prefix == '㍲') ? DECA + unit : prefix + unit; } /** * Returns the unit for the given symbol, taking the SI prefix in account. The given string is usually a single symbol * like "km", but may be an expression like "m³" or "m/s" if the given symbol is explicitly registered as an item that * {@link Units#get(String)} recognizes. This method does not perform any arithmetic operation on {@code Unit}, * except a check for the exponent. * * @param uom a symbol compliant with the rules documented in {@link AbstractUnit#symbol}. * @return the unit for the given symbol, or {@code null} if no unit is found. */ static Unit getUnit(final String uom) { Unit unit = Units.get(uom); if (unit == null && uom.length() >= 2) { int s = 1; char prefix = uom.charAt(0); if (prefix == 'd' && uom.charAt(1) == 'a') { prefix = '㍲'; // Converse of above 'concat(char, String)' method. s = 2; // Skip "da", which we represent by '㍲'. } unit = Units.get(uom.substring(s)); if (AbstractUnit.isPrefixable(unit)) { LinearConverter c = Prefixes.converter(prefix); if (c != null) { String symbol = unit.getSymbol(); final int power = ConventionalUnit.power(symbol); if (power != 0) { if (power != 1) { c = LinearConverter.pow(c, power, false); } symbol = Prefixes.concat(prefix, symbol); return new ConventionalUnit<>((AbstractUnit) unit, c, symbol.intern(), (byte) 0, (short) 0); } } } unit = null; } return unit; } /** * If the given system unit should be replaced by pseudo-unit for the purpose of formatting, * returns that pseudo-unit. Otherwise returns {@code null}. This method is for handling the * Special case of {@link Units#KILOGRAM}, to be replaced by {@link Units#GRAM} so a prefix * can be computed. The kilogram may appear in an expression like "kg/m", which we want to * replace by "g/m". We do that by dividing the unit by 1000 (the converter for "milli" prefix). */ @SuppressWarnings("unchecked") static > ConventionalUnit pseudoSystemUnit(final SystemUnit unit) { if ((unit.scope & ~UnitRegistry.SI) == 0 && unit.dimension.numeratorIs('M')) { if (unit == Units.KILOGRAM) { return (ConventionalUnit) Units.GRAM; // Optimization for a common case. } else { String symbol = unit.getSymbol(); if (symbol != null && symbol.length() >= 3 && symbol.startsWith("kg") && !AbstractUnit.isSymbolChar(symbol.codePointAt(2))) { symbol = symbol.substring(1); UnitConverter c = converter('m'); return new ConventionalUnit<>(unit, c, symbol, UnitRegistry.PREFIXABLE, (short) 0).unique(symbol); } } } return null; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 11942 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-utility/src/main/java/org/apache/sis/measure/Prefixes.java/#L37-L216 | 1 | 1775 | 11942 | minor |
| 26 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 26 | 695 | critical |
| 2009 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12742 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/protocol/src/main/java/org/apache/drill/exec/proto/UserProtos.java/#L19445-L20118 | 2 | 2009 | 12742 | critical | ||
| 1618 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 11476 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1618 | 11476 | major |
| 1361 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10778 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 1361 | 10778 | minor |
| 3170 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 4457 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 3170 | 4457 | minor |
| 555 | { "YES I found bad smells": true, "the bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | long method | t | t | f | long method | blob | 0 | 5607 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 2 | 555 | 5607 | critical |
| 1573 | {"message":"YES I found bad smells","the bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
blob | data class | t | t | f | data class | blob | 0 | 11342 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 1 | 1573 | 11342 | critical |
| 750 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue public abstract class UPlaceholderExpression extends UExpression { static UPlaceholderExpression create( PlaceholderMethod placeholder, Iterable arguments) { ImmutableList placeholderParams = placeholder.parameters().asList(); ImmutableList argumentsList = ImmutableList.copyOf(arguments); ImmutableMap.Builder builder = ImmutableMap.builder(); for (int i = 0; i < placeholderParams.size(); i++) { builder.put(placeholderParams.get(i), argumentsList.get(i)); } return new AutoValue_UPlaceholderExpression(placeholder, builder.build()); } abstract PlaceholderMethod placeholder(); abstract ImmutableMap arguments(); public static final class PlaceholderParamIdent extends JCIdent { final UVariableDecl param; PlaceholderParamIdent(UVariableDecl param, Context context) { super(Names.instance(context).fromString(param.getName().contents()), null); this.param = checkNotNull(param); } } static class UncheckedCouldNotResolveImportException extends RuntimeException { UncheckedCouldNotResolveImportException(CouldNotResolveImportException e) { super(e); } @Override public synchronized CouldNotResolveImportException getCause() { return (CouldNotResolveImportException) super.getCause(); } } static TreeCopier copier( final Map arguments, Inliner inliner) { return new TreeCopier(inliner.maker()) { @Override public T copy(T tree, Inliner inliner) { if (tree == null) { return null; } T result = super.copy(tree, inliner); if (result.toString().equals(tree.toString())) { return tree; } else { return result; } } @Override public JCTree visitIdentifier(IdentifierTree node, Inliner inliner) { if (node instanceof PlaceholderParamIdent) { try { return arguments.get(((PlaceholderParamIdent) node).param).inline(inliner); } catch (CouldNotResolveImportException e) { throw new UncheckedCouldNotResolveImportException(e); } } else { return super.visitIdentifier(node, inliner); } } }; } @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { /* * Copy the original source bound to the placeholder, except anywhere we matched a placeholder * parameter, replace that with the corresponding expression in this invocation. */ try { return copier(arguments(), inliner) .copy(inliner.getBinding(placeholder().exprKey()), inliner); } catch (UncheckedCouldNotResolveImportException e) { throw e.getCause(); } } @Override public Kind getKind() { return Kind.OTHER; } @Override public R accept(TreeVisitor visitor, D data) { return visitor.visitOther(this, data); } public boolean reverify(Unifier unifier) { return MoreObjects.firstNonNull( new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()) .scan(unifier.getBinding(placeholder().exprKey()), unifier), true); } @Override protected Choice defaultAction(Tree node, Unifier unifier) { // for now we only match JCExpressions if (placeholder().returnType().equals(UPrimitiveType.VOID) || !(node instanceof JCExpression)) { return Choice.none(); } final JCExpression expr = (JCExpression) node; PlaceholderVerificationVisitor verification = new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()); if (!verification.scan(node, unifier) || !verification.allRequiredMatched()) { return Choice.none(); } /* * We copy the tree with a TreeCopier, replacing matches for the parameters with * PlaceholderParamIdents, and updating unifierHolder as we unify things, including forbidding * references to local variables, etc. */ Choice> states = PlaceholderUnificationVisitor.create(TreeMaker.instance(unifier.getContext()), arguments()) .unifyExpression( expr, PlaceholderUnificationVisitor.State.create( List.nil(), unifier, null)); return states.thenOption( (PlaceholderUnificationVisitor.State state) -> { if (ImmutableSet.copyOf(state.seenParameters()) .containsAll(placeholder().requiredParameters())) { Unifier resultUnifier = state.unifier(); JCExpression prevBinding = resultUnifier.getBinding(placeholder().exprKey()); if (prevBinding != null) { return prevBinding.toString().equals(state.result().toString()) ? Optional.of(resultUnifier) : Optional.absent(); } JCExpression result = state.result(); if (!placeholder() .matcher() .matches(result, UMatches.makeVisitorState(expr, resultUnifier))) { return Optional.absent(); } result.type = expr.type; resultUnifier.putBinding(placeholder().exprKey(), result); return Optional.of(resultUnifier); } else { return Optional.absent(); } }); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 7028 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java/#L45-L201 | 1 | 750 | 7028 | major |
| 2443 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14485 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 2 | 2443 | 14485 | minor |
| 2438 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14474 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 2438 | 14474 | minor |
| 2560 | YES I found bad smells 1. Long method 2. Feature envy 3. Duplicate code (e.g. setting button enabled in multiple methods) 4. Low cohesion (e.g. setting file name in getFileName() method instead of in the addFile() method) 5. Poor naming conventions (e.g. using generic names like "file" instead of more descriptive names) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } } |
blob | Long method2 Feature envy3 Duplicate code (eg setting button enabled in multiple methods)4 Low cohesion (eg setting file name in getFileName() method instead of in the addFile() method)5 Poor naming conventions (eg using generic names like "file" instead of more descriptive names) | t | f | f | . Long method2. Feature envy3. Duplicate code (e.g. setting button enabled in multiple methods)4. Low cohesion (e.g. setting file name in getFileName() method instead of in the addFile() method)5. Poor naming conventions (e.g. using generic names like "file" instead of more descriptive names) | blob | 0 | 14836 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 | 2 | 2560 | 14836 | minor |
| 740 | YES, I found bad smells. The bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class getJobSummary_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getJobSummary_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getJobSummary_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | blob | 0 | 6974 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/ReadOnlyScheduler.java/#L3175-L3220 | 2 | 740 | 6974 | minor |
| 1356 | YES I found bad smells the bad smells are: Feature envy, Long method, Data class, Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MissedUpdatesFinder extends MissedUpdatesFinderBase { private long ourHighThreshold; // 80th percentile private long ourHighest; // currently just used for logging/debugging purposes private String logPrefix; private long nUpdates; MissedUpdatesFinder(List ourUpdates, String logPrefix, long nUpdates, long ourLowThreshold, long ourHighThreshold) { super(ourUpdates, ourLowThreshold); this.logPrefix = logPrefix; this.ourHighThreshold = ourHighThreshold; this.ourHighest = ourUpdates.get(0); this.nUpdates = nUpdates; } public MissedUpdatesRequest find(List otherVersions, Object updateFrom, Supplier canHandleVersionRanges) { otherVersions.sort(absComparator); if (debug) { log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom); } long otherHigh = percentile(otherVersions, .2f); long otherLow = percentile(otherVersions, .8f); long otherHighest = otherVersions.get(0); if (ourHighThreshold < otherLow) { // Small overlap between version windows and ours is older // This means that we might miss updates if we attempted to use this method. // Since there exists just one replica that is so much newer, we must // fail the sync. log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (ourLowThreshold > otherHigh && ourHighest >= otherHighest) { // Small overlap between windows and ours is newer. // Using this list to sync would result in requesting/replaying results we don't need // and possibly bringing deleted docs back to life. log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); // Because our versions are newer, IndexFingerprint with the remote would not match us. // We return true on our side, but the remote peersync with us should fail. return MissedUpdatesRequest.ALREADY_IN_SYNC; } boolean completeList = otherVersions.size() < nUpdates; MissedUpdatesRequest updatesRequest; if (canHandleVersionRanges.get()) { updatesRequest = handleVersionsWithRanges(otherVersions, completeList); } else { updatesRequest = handleIndividualVersions(otherVersions, completeList); } if (updatesRequest.totalRequestedUpdates > nUpdates) { log.info("{} PeerSync will fail because number of missed updates is more than:{}", logPrefix, nUpdates); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (updatesRequest == MissedUpdatesRequest.EMPTY) { log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); } return updatesRequest; } } |
blob | Feature envy, Long method, Data class, Duplicate code | t | f | f | Feature envy, Long method, Data class, Duplicate code | blob | 0 | 10769 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/PeerSync.java/#L787-L856 | 2 | 1356 | 10769 | minor |
| 1659 | YES I found bad smells The bad smells are: 1. Empty constructor 2. Public fields | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Empty constructor2 Public fields | t | f | f | . Empty constructor2. Public fields | data class | 0 | 11607 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 1659 | 11607 | minor |
| 2243 | YES I found bad smellsThe bad smells are: 1. Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class. 2. Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists. These methods could be refactored to have fewer parameters or split into smaller, more specific methods. 3. Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter. These methods could be refactored to use a single method that handles both cases. 4. Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects. This inconsistency in naming could lead to confusion for the users. 5. No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods. This lack of documentation could make it difficult for users to understand the purpose and usage of the class. 6. Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users. This could potentially leave users confused and unsure of how to properly use the class. 7. Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose. These methods should either be implemented or removed to avoid confusion for users. 8. Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int". This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class2 Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists These methods could be refactored to have fewer parameters or split into smaller, more specific methods3 Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter These methods could be refactored to use a single method that handles both cases4 Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects This inconsistency in naming could lead to confusion for the users5 No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods This lack of documentation could make it difficult for users to understand the purpose and usage of the class6 Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users This could potentially leave users confused and unsure of how to properly use the class7 Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose These methods should either be implemented or removed to avoid confusion for users8 Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int" This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value | t | f | f | . Feature envy: The method signatures for getHeaders(), getHost(), getSubProtocols(), getParameterMap(), getRequestURI(), and getQueryString() suggest that they may be better suited as methods on a different class.2. Long parameter list: The methods setCookie(), setExtensions(), setHttpVersion(), setMethod(), setHeader(), setHeaders(), setSubProtocols() all have long parameter lists. These methods could be refactored to have fewer parameters or split into smaller, more specific methods.3. Duplicate code: The method addExtensions() has two almost identical versions of the same code, one taking in an ExtensionConfig parameter and the other taking in a String parameter. These methods could be refactored to use a single method that handles both cases.4. Inconsistent naming: The method getCookies() returns a List of Cookie objects, while the method getExtensions() returns a List of ExtensionConfig objects. This inconsistency in naming could lead to confusion for the users.5. No comments or documentation: Although there are some comments scattered throughout the code, there is no overall description of the class or its methods. This lack of documentation could make it difficult for users to understand the purpose and usage of the class.6. Deprecated method: The method clearHeaders() is marked as deprecated, but there is no explanation or alternative provided for users. This could potentially leave users confused and unsure of how to properly use the class.7. Unused methods: The methods getHost(), getHttpVersion() and getMethod() are all unimplemented and do not serve any purpose. These methods should either be implemented or removed to avoid confusion for users.8. Magic numbers: The method getHeaderInt() takes in a header name as a parameter, but the method name itself mentions "int". This could potentially lead to confusion for users as they may expect the method to return an int value instead of a String value. | data class | 0 | 13626 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 2243 | 13626 | major |
| 654 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 6390 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 654 | 6390 | major |
| 3986 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 10501 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 1 | 3986 | 10501 | minor |
| 2215 | {"message": "YES I found bad smells", "bad smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | blob | t | t | f | blob | data class | 0 | 13529 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 1 | 2215 | 13529 | minor |
| 302 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (method is accessing multiple data from the associated protocol) 3. Redundant comments/documentation (ex: "// Set the list of Cookies on the request") 4. Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions") 5. Deprecated method still present in the interface but explicitly marked as deprecated. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | Long method2 Feature envy (method is accessing multiple data from the associated protocol)3 Redundant comments/documentation (ex: "// Set the list of Cookies on the request")4 Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions")5 Deprecated method still present in the interface but explicitly marked as deprecated | t | f | f | . Long method2. Feature envy (method is accessing multiple data from the associated protocol)3. Redundant comments/documentation (ex: "// Set the list of Cookies on the request")4. Inconsistent naming convention for methods (ex: "getHeaders", "getCookies", "getExtensions")5. Deprecated method still present in the interface but explicitly marked as deprecated. | data class | 0 | 3165 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 302 | 3165 | major |
| 1205 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10288 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 1205 | 10288 | minor |
| 482 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void removePipeline(Pipeline pipeline) { for (DatanodeDetails details : pipeline.getNodes()) { UUID dnId = details.getUuid(); dn2ObjectMap.computeIfPresent(dnId, (k, v) -> { v.remove(pipeline.getId()); return v; }); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4708 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/states/Node2PipelineMap.java/#L67-L76 | 1 | 482 | 4708 | minor |
| 855 | YES, I found bad smells -1. Duplicated code -2. Large class -3. Long method -4. Feature envy -5. Poor naming conventions (e.g. getAssociatedLocations, getAssociatedSrcRelativePath) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugTraceBasedRegion extends AbstractTraceRegion { private final DebugTraceRegion delegate; protected DebugTraceBasedRegion(AbstractTraceRegion parent, DebugTraceRegion delegate) { super(parent); this.delegate = delegate; for (DebugTraceRegion child : delegate.getNestedRegions()) new DebugTraceBasedRegion(this, child); } private LocationData convert(DebugLocationData data) { SourceRelativeURI uri = data.getPath() != null ? new SourceRelativeURI(data.getPath()) : null; return new LocationData(data.getOffset(), data.getLength(), data.getLineNumber(), data.getEndLineNumber(), uri); } @Override public List getAssociatedLocations() { List result = Lists.newArrayListWithCapacity(delegate.getAssociations().size()); for (DebugLocationData data : delegate.getAssociations()) result.add(convert(data)); return result; } @Override public SourceRelativeURI getAssociatedSrcRelativePath() { SourceRelativeURI path = super.getAssociatedSrcRelativePath(); if (path != null) return path; return getAssociatedSrcRelativePath(delegate); } protected SourceRelativeURI getAssociatedSrcRelativePath(DebugTraceRegion region) { for (DebugLocationData associated : region.getAssociations()) { URI uri = associated.getPath(); if (uri != null) return new SourceRelativeURI(uri); } EObject container = region.eContainer(); if (container instanceof DebugTraceRegion) return getAssociatedSrcRelativePath((DebugTraceRegion) container); return null; } @Override public int getMyEndLineNumber() { return delegate.getMyEndLineNumber(); } @Override public int getMyLength() { return delegate.getMyLength(); } @Override public int getMyLineNumber() { return delegate.getMyLineNumber(); } @Override public int getMyOffset() { return delegate.getMyOffset(); } @Override public boolean isUseForDebugging() { return delegate.isUseForDebugging(); } } |
data class | Duplicated code -2 Large class -3 Long method -4 Feature envy -5 Poor naming conventions (eg getAssociatedLocations, getAssociatedSrcRelativePath) | t | f | f | . Duplicated code -2. Large class -3. Long method -4. Feature envy -5. Poor naming conventions (e.g. getAssociatedLocations, getAssociatedSrcRelativePath) | data class | 0 | 7879 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.builder/src/org/eclipse/xtext/builder/trace/DebugTraceBasedRegion.java/#L24-L93 | 2 | 855 | 7879 | major |
| 563 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OdaDimensionState extends ReportElementState { /** * The dimension being created. */ protected Dimension element = null; /** * Constructs dimension state with the design parser handler, the container * element and the container property name of the report element. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param prop * the slot in which this element appears */ public OdaDimensionState( ModuleParserHandler handler, DesignElement theContainer, String prop ) { super( handler, theContainer, prop ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.parser.ReportElementState#getElement() */ public DesignElement getElement( ) { return element; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(org.xml.sax.Attributes) */ public void parseAttrs( Attributes attrs ) throws XMLParserException { element = new OdaDimension( ); initElement( attrs, true ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5681 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/parser/OdaDimensionState.java/#L25-L74 | 2 | 563 | 5681 | minor |
| 1362 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10779 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1362 | 10779 | minor |
| 2256 | Yes I found bad smells. The bad smells are: 1. Feature envy, 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Feature envy, 2 Long method | t | f | f | . Feature envy, 2. Long method. | data class | 0 | 13691 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 2256 | 13691 | major |
| 1783 | { "message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11967 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 2 | 1783 | 11967 | critical |
| 2630 | {"answer": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15098 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 1 | 2630 | 15098 | minor |
| 2022 | {"message": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12792 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 | 1 | 2022 | 12792 | minor |
| 49 | { "answer": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 856 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 2 | 49 | 856 | minor |
| 5458 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 528 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 2 | 5458 | 528 | critical |
| 1378 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10816 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 1378 | 10816 | minor |
| 1139 | YES I found bad smells the bad smells are: 1. Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles". 2. Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided. 3. Missing access modifiers - the access modifiers for the class and methods are not specified explicitly. 4. Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable. 5. Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class. 6. Lack of encapsulation - the roles field is public and can be accessed and modified directly. 7. Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles" 2 Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided 3 Missing access modifiers - the access modifiers for the class and methods are not specified explicitly 4 Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable 5 Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class 6 Lack of encapsulation - the roles field is public and can be accessed and modified directly 7 Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly | t | f | f | . Inconsistent naming convention - the class name "Roles" is not consistent with the variable name "roles". 2. Incomplete constructor - the default constructor is not used and only one parameterized constructor is provided. 3. Missing access modifiers - the access modifiers for the class and methods are not specified explicitly. 4. Magic number - the namespace string is hard-coded as a magic number instead of being defined as a constant or variable. 5. Unused variable - the parameterized constructor takes in a "roles" parameter but it is not used in the constructor or anywhere else in the class. 6. Lack of encapsulation - the roles field is public and can be accessed and modified directly. 7. Feature envy - the getRoles() method is returning the "roles" field instead of just accessing it directly. | data class | 0 | 10076 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 2 | 1139 | 10076 | major |
| 3358 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected String getTableStatus( Statement sStatement ) throws SQLException { ResultSet statusResultSet = sStatement.executeQuery( "show table status" ); StringBuilder statusString = new StringBuilder(); int numColumns = statusResultSet.getMetaData().getColumnCount(); while ( statusResultSet.next() ) { statusString.append( "\n" ); for ( int i = 1; i <= numColumns; i++ ) { statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " [" + statusResultSet.getString( i ) + "] | " ); } } return statusString.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6369 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java/#L212-L228 | 1 | 3358 | 6369 | minor |
| 442 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileIODecorator extends AbstractFileIO { /** File I/O delegate */ protected final FileIO delegate; /** * * @param delegate File I/O delegate */ public FileIODecorator(FileIO delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public int getFileSystemBlockSize() { return delegate.getFileSystemBlockSize(); } /** {@inheritDoc} */ @Override public long getSparseSize() { return delegate.getSparseSize(); } /** {@inheritDoc} */ @Override public int punchHole(long pos, int len) { return delegate.punchHole(pos, len); } /** {@inheritDoc} */ @Override public long position() throws IOException { return delegate.position(); } /** {@inheritDoc} */ @Override public void position(long newPosition) throws IOException { delegate.position(newPosition); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf) throws IOException { return delegate.read(destBuf); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf, long position) throws IOException { return delegate.read(destBuf, position); } /** {@inheritDoc} */ @Override public int read(byte[] buf, int off, int len) throws IOException { return delegate.read(buf, off, len); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf) throws IOException { return delegate.write(srcBuf); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf, long position) throws IOException { return delegate.write(srcBuf, position); } /** {@inheritDoc} */ @Override public int write(byte[] buf, int off, int len) throws IOException { return delegate.write(buf, off, len); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int sizeBytes) throws IOException { return delegate.map(sizeBytes); } /** {@inheritDoc} */ @Override public void force() throws IOException { delegate.force(); } /** {@inheritDoc} */ @Override public void force(boolean withMetadata) throws IOException { delegate.force(withMetadata); } /** {@inheritDoc} */ @Override public long size() throws IOException { return delegate.size(); } /** {@inheritDoc} */ @Override public void clear() throws IOException { delegate.clear(); } /** {@inheritDoc} */ @Override public void close() throws IOException { delegate.close(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 4303 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/FileIODecorator.java/#L27-L123 | 2 | 442 | 4303 | minor |
| 493 | YES I found bad smells! the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4960 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 2 | 493 | 4960 | minor |
| 93 | {"response": "YES I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 1252 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 1 | 93 | 1252 | major |
| 2375 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14315 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 2 | 2375 | 14315 | minor |
| 2004 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | long method | t | t | f | long method | blob | 0 | 12718 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 1 | 2004 | 12718 | major |
| 1910 | YES I found bad smells the bad smells are: 1. Feature envy 2. Magic numbers 3. High coupling 4. Duplicate code 5. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
blob | Feature envy2 Magic numbers3 High coupling4 Duplicate code5 Long method | t | f | f | . Feature envy2. Magic numbers3. High coupling4. Duplicate code5. Long method | blob | 0 | 12398 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 2 | 1910 | 12398 | minor |
| 1658 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | t | f | f | data class | 0 | 11602 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 1658 | 11602 | minor | ||
| 2662 | YES I found bad smells the bad smells are: 1. Long method 2. Data clumps 3. Class data should be private 4. Inappropriate comments 5. Inconsistent indentation 6. Magic numbers (e.g. BUFFER_SIZE = 1500) 7. Unused variables (e.g. buffer, offset) 8. Bad variable naming (e.g. i, ex, addr) 9. Duplicated code (e.g. creating and sending ganglia messages has duplicate code) 10. Inconsistent use of access modifiers 11. Multiple responsibilities (GangliaServer has the responsibilities of creating ganglia messages and sending them, but also implementing the MonitorService interface) 12. Long parameter list (the configure method has too many parameters) 13. Use of deprecated code (e.g. getLogger and warn) 14. Empty catch blocks 15. Nested if statements 16. Mixing different styles of error handling (exceptions and return values) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | Long method 2 Data clumps 3 Class data should be private 4 Inappropriate comments 5 Inconsistent indentation 6 Magic numbers (eg BUFFER_SIZE = | t | f | f | . Long method 2. Data clumps 3. Class data should be private 4. Inappropriate comments 5. Inconsistent indentation 6. Magic numbers (e.g. BUFFER_SIZE = | data class | 0 | 15197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2662 | 15197 | minor |
| 2239 | YES I found bad smells the bad smells are: 1. Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability. 2. Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant. 3. Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability2 Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant3 Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain | t | f | f | . Annotation overuse: the code contains multiple annotations which could indicate a lack of organization and readability.2. Magic numbers: the value "0" in the getTabNames() method is a magic number and should be replaced with a descriptive constant.3. Inconsistent formatting: the code has inconsistent spacing and indentation, making it hard to read and maintain. | data class | 0 | 13618 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 2 | 2239 | 13618 | minor |
| 1740 | YES, bad smells are: Long method, duplicated code, feature envy, data clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface CassandraSieveRepositoryModule { CassandraModule MODULE = CassandraModule.builder() .table(CassandraSieveTable.TABLE_NAME) .comment("Holds SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveTable.USER_NAME, text()) .addClusteringColumn(CassandraSieveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveTable.SCRIPT_CONTENT, text()) .addColumn(CassandraSieveTable.IS_ACTIVE, cboolean()) .addColumn(CassandraSieveTable.SIZE, bigint())) .table(CassandraSieveSpaceTable.TABLE_NAME) .comment("Holds per user current space occupied by SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveSpaceTable.USER_NAME, text()) .addColumn(CassandraSieveSpaceTable.SPACE_USED, counter())) .table(CassandraSieveQuotaTable.TABLE_NAME) .comment("Holds per user size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveQuotaTable.USER_NAME, text()) .addColumn(CassandraSieveQuotaTable.QUOTA, bigint())) .table(CassandraSieveClusterQuotaTable.TABLE_NAME) .comment("Holds default size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveClusterQuotaTable.NAME, text()) .addColumn(CassandraSieveClusterQuotaTable.VALUE, bigint())) .table(CassandraSieveActiveTable.TABLE_NAME) .comment("Denormalisation table. Allows per user direct active SIEVE script retrieval.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveActiveTable.USER_NAME, text()) .addColumn(CassandraSieveActiveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveActiveTable.DATE, timestamp())) .build(); } |
blob | Long method, duplicated code, feature envy, data clumps | t | f | f | Long method, duplicated code, feature envy, data clumps | blob | 0 | 11840 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-cassandra/src/main/java/org/apache/james/sieve/cassandra/CassandraSieveRepositoryModule.java/#L35-L74 | 2 | 1740 | 11840 | major |
| 2557 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14832 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 1 | 2557 | 14832 | minor |
| 553 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 5576 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 | 1 | 553 | 5576 | minor |
| 19 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int getSiblingIndexWithClassName(Element element, String className) { int index = 0; while (element != null) { element = (Element) element.getPreviousSibling(); if (element != null && Elements.hasClassName(className, element)) { ++index; } } return index; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 679 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/dom/DomUtils.java/#L171-L180 | 2 | 19 | 679 | major |
| 4051 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10700 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 4051 | 10700 | major |
| 1779 | { "message": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | blob | t | t | f | blob | data class | 0 | 11959 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 1779 | 11959 | critical |
| 2124 | YES I found bad smells the bad smells are: 1. Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently. 2. Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain. 3. Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them. 4. Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed. 5. Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together. 6. Inconsistent naming - Some variables and methods use camelCase while others use snake_case. 7. Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it. 8. Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code. 9. Magic numbers - Some numbers, such as -1 and 0, are used as parameters or compared to, but their purpose or significance is not clear. 10. Complex code - Some methods have complex calculations and logic that could be simplified and made more readable. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently2 Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain3 Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them4 Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed5 Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together6 Inconsistent naming - Some variables and methods use camelCase while others use snake_case7 Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it8 Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code9 Magic numbers - Some numbers, such as - | t | f | f | . Feature envy - TextAndButtonSection class is calling methods and accessing properties of other classes too frequently.2. Long method - Some methods in the TextAndButtonSection class are longer than they should be, making the code harder to read and maintain.3. Primitive obsession - Primitive data types such as int and boolean are used instead of creating specific classes for them.4. Commented out code - There are several lines of code that have been commented out, indicating that they may have been used at one point but are no longer needed.5. Data clump - Several properties such as buttonText, buttonTooltipText, and buttonWidth are all related to the same GUI element (the button), but are declared separately instead of being grouped together.6. Inconsistent naming - Some variables and methods use camelCase while others use snake_case.7. Unnecessary boolean checks - In the createSection() method, the condition in the if statement is always true, making it unnecessary to check it.8. Unused variables - Several variables, such as oldValue and provider, are declared but not used anywhere in the code.9. Magic numbers - Some numbers, such as - | data class | 0 | 13216 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 2124 | 13216 | major |
| 1870 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Inconsistent formatting, 5. Useless comments, 6. Large class, 7. Confusing variable names, 8. Inefficient data types. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | Long method, 2 Feature envy, 3 Duplicate code, 4 Inconsistent formatting, 5 Useless comments, 6 Large class, 7 Confusing variable names, 8 Inefficient data types | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Inconsistent formatting, 5. Useless comments, 6. Large class, 7. Confusing variable names, 8. Inefficient data types. | blob | 0 | 12247 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 2 | 1870 | 12247 | major |
| 1888 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12300 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 2 | 1888 | 12300 | critical |
| 38 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOG.info("GroupService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteGroupByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 761 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java/#L203-L212 | 1 | 38 | 761 | major |
| 2624 | YES, I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicated Code 4. Inconsistent Naming Conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | Long Method 2 Feature Envy 3 Duplicated Code4 Inconsistent Naming Conventions | t | f | f | . Long Method 2. Feature Envy 3. Duplicated Code4. Inconsistent Naming Conventions | data class | 0 | 15072 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 2624 | 15072 | minor |
| 750 | YES I found bad smells the bad smells are: 1.Long method 2.Nested Try/Catch Block 3.Inappropriate naming of variables and methods 4.Complex and nested conditional statements 5.Multiple responsibilities in a single class 6.Lack of proper comments and documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue public abstract class UPlaceholderExpression extends UExpression { static UPlaceholderExpression create( PlaceholderMethod placeholder, Iterable arguments) { ImmutableList placeholderParams = placeholder.parameters().asList(); ImmutableList argumentsList = ImmutableList.copyOf(arguments); ImmutableMap.Builder builder = ImmutableMap.builder(); for (int i = 0; i < placeholderParams.size(); i++) { builder.put(placeholderParams.get(i), argumentsList.get(i)); } return new AutoValue_UPlaceholderExpression(placeholder, builder.build()); } abstract PlaceholderMethod placeholder(); abstract ImmutableMap arguments(); public static final class PlaceholderParamIdent extends JCIdent { final UVariableDecl param; PlaceholderParamIdent(UVariableDecl param, Context context) { super(Names.instance(context).fromString(param.getName().contents()), null); this.param = checkNotNull(param); } } static class UncheckedCouldNotResolveImportException extends RuntimeException { UncheckedCouldNotResolveImportException(CouldNotResolveImportException e) { super(e); } @Override public synchronized CouldNotResolveImportException getCause() { return (CouldNotResolveImportException) super.getCause(); } } static TreeCopier copier( final Map arguments, Inliner inliner) { return new TreeCopier(inliner.maker()) { @Override public T copy(T tree, Inliner inliner) { if (tree == null) { return null; } T result = super.copy(tree, inliner); if (result.toString().equals(tree.toString())) { return tree; } else { return result; } } @Override public JCTree visitIdentifier(IdentifierTree node, Inliner inliner) { if (node instanceof PlaceholderParamIdent) { try { return arguments.get(((PlaceholderParamIdent) node).param).inline(inliner); } catch (CouldNotResolveImportException e) { throw new UncheckedCouldNotResolveImportException(e); } } else { return super.visitIdentifier(node, inliner); } } }; } @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { /* * Copy the original source bound to the placeholder, except anywhere we matched a placeholder * parameter, replace that with the corresponding expression in this invocation. */ try { return copier(arguments(), inliner) .copy(inliner.getBinding(placeholder().exprKey()), inliner); } catch (UncheckedCouldNotResolveImportException e) { throw e.getCause(); } } @Override public Kind getKind() { return Kind.OTHER; } @Override public R accept(TreeVisitor visitor, D data) { return visitor.visitOther(this, data); } public boolean reverify(Unifier unifier) { return MoreObjects.firstNonNull( new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()) .scan(unifier.getBinding(placeholder().exprKey()), unifier), true); } @Override protected Choice defaultAction(Tree node, Unifier unifier) { // for now we only match JCExpressions if (placeholder().returnType().equals(UPrimitiveType.VOID) || !(node instanceof JCExpression)) { return Choice.none(); } final JCExpression expr = (JCExpression) node; PlaceholderVerificationVisitor verification = new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()); if (!verification.scan(node, unifier) || !verification.allRequiredMatched()) { return Choice.none(); } /* * We copy the tree with a TreeCopier, replacing matches for the parameters with * PlaceholderParamIdents, and updating unifierHolder as we unify things, including forbidding * references to local variables, etc. */ Choice> states = PlaceholderUnificationVisitor.create(TreeMaker.instance(unifier.getContext()), arguments()) .unifyExpression( expr, PlaceholderUnificationVisitor.State.create( List.nil(), unifier, null)); return states.thenOption( (PlaceholderUnificationVisitor.State state) -> { if (ImmutableSet.copyOf(state.seenParameters()) .containsAll(placeholder().requiredParameters())) { Unifier resultUnifier = state.unifier(); JCExpression prevBinding = resultUnifier.getBinding(placeholder().exprKey()); if (prevBinding != null) { return prevBinding.toString().equals(state.result().toString()) ? Optional.of(resultUnifier) : Optional.absent(); } JCExpression result = state.result(); if (!placeholder() .matcher() .matches(result, UMatches.makeVisitorState(expr, resultUnifier))) { return Optional.absent(); } result.type = expr.type; resultUnifier.putBinding(placeholder().exprKey(), result); return Optional.of(resultUnifier); } else { return Optional.absent(); } }); } } |
blob | Long method2Nested Try/Catch Block3Inappropriate naming of variables and methods4Complex and nested conditional statements5Multiple responsibilities in a single class6Lack of proper comments and documentation | t | f | f | .Long method2.Nested Try/Catch Block3.Inappropriate naming of variables and methods4.Complex and nested conditional statements5.Multiple responsibilities in a single class6.Lack of proper comments and documentation | blob | 0 | 7028 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java/#L45-L201 | 2 | 750 | 7028 | major |
| 1253 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | f | f | f | data class | 0 | 10456 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 1253 | 10456 | minor | ||
| 5153 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14424 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 1 | 5153 | 14424 | critical | ||
| 1577 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11353 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 1577 | 11353 | minor |
| 1600 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent indentation 5. Undescriptive name for variables 6. Use of public access modifiers for fields 7. Use of inline comments 8. Use of Magic numbers (e.g. 0) 9. Use of hard-coded strings 10. Code duplication within the same class 11. Use of incorrect types for variables (e.g. String instead of URI) 12. Inconsistent spacing and formatting 13. Too many parameters in methods 14. Poor exception handling 15. Violation of Single Responsibility Principle 16. Lack of encapsulation for fields and methods 17. Use of conditional statements to handle null values 18. Inefficient use of data structures 19. Unnecessary casting of variables 20. Use of static methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WebServer { public static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private HttpServer2 httpServer; private final HasConfig conf; private InetSocketAddress httpAddress; private InetSocketAddress httpsAddress; protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver"; public WebServer(HasConfig conf) { this.conf = conf; } public HasConfig getConf() { return conf; } private void init() { final String pathSpec = "/has/v1/*"; // add has packages httpServer.addJerseyResourcePackage(AsRequestApi.class .getPackage().getName(), pathSpec); } public void defineFilter() { String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType.equals("kerberos")) { // add authentication filter for webhdfs final String className = conf.getString( WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY, WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT); final String name = className; Map params = getAuthFilterParams(conf); String kadminPathSpec = "/has/v1/kadmin/*"; String hadminPathSpec = "/has/v1/hadmin/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className, params, new String[]{kadminPathSpec, hadminPathSpec}); HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className + ")"); } } public void defineConfFilter() { String confFilterName = ConfFilter.class.getName(); String confPath = "/has/v1/conf/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName, getAuthFilterParams(conf), new String[]{confPath}); HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName + ")"); } private Map getAuthFilterParams(HasConfig conf) { Map params = new HashMap<>(); String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType != null && !authType.isEmpty()) { params.put(AuthenticationFilter.AUTH_TYPE, authType); } String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY); if (principal != null && !principal.isEmpty()) { try { principal = SecurityUtil.getServerPrincipal(principal, getHttpsAddress().getHostName()); } catch (IOException e) { LOG.warn("Errors occurred when get server principal. " + e.getMessage()); } params.put(KerberosAuthenticationHandler.PRINCIPAL, principal); } String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY); if (keytab != null && !keytab.isEmpty()) { params.put(KerberosAuthenticationHandler.KEYTAB, keytab); } String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES); if (rule != null && !rule.isEmpty()) { params.put(KerberosAuthenticationHandler.NAME_RULES, rule); } else { params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT"); } return params; } public InetSocketAddress getBindAddress() { if (httpAddress != null) { return httpAddress; } else if (httpsAddress != null) { return httpsAddress; } else { return null; } } /** * for information related to the different configuration options and * Http Policy is decided. * * @throws HasException HAS exception when starting web server */ public void start() throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); final String bindHost = conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY); InetSocketAddress httpAddr = null; if (policy.isHttpEnabled()) { final String httpAddrString = conf.getString( WebConfigKey.HAS_HTTP_ADDRESS_KEY, WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT); httpAddr = NetUtils.createSocketAddr(httpAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort()); } LOG.info("Get the http address: " + httpAddr); } InetSocketAddress httpsAddr = null; if (policy.isHttpsEnabled()) { final String httpsAddrString = conf.getString( WebConfigKey.HAS_HTTPS_ADDRESS_KEY, WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT); httpsAddr = NetUtils.createSocketAddr(httpsAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort()); } LOG.info("Get the https address: " + httpsAddr); } HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has"); try { httpServer = builder.build(); } catch (IOException e) { throw new HasException("Errors occurred when building http server. " + e.getMessage()); } init(); try { httpServer.start(); } catch (IOException e) { throw new HasException("Errors occurred when starting http server. " + e.getMessage()); } int connIdx = 0; if (policy.isHttpEnabled()) { httpAddress = httpServer.getConnectorAddress(connIdx++); if (httpAddress != null) { conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, NetUtils.getHostPortString(httpAddress)); } } if (policy.isHttpsEnabled()) { httpsAddress = httpServer.getConnectorAddress(connIdx); if (httpsAddress != null) { conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, NetUtils.getHostPortString(httpsAddress)); } } } public void setWebServerAttribute(HasServer hasServer) { httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer); } public static HasServer getHasServerFromContext(ServletContext context) { return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY); } /** * Get http policy. * * @param conf the HAS config * @return HttpConfig.Policy the policy */ public HttpConfig.Policy getHttpPolicy(HasConfig conf) { String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY, WebConfigKey.HAS_HTTP_POLICY_DEFAULT); HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr); if (policy == null) { throw new HadoopIllegalArgumentException("Unrecognized value '" + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY); } conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name()); return policy; } /** * Return a HttpServer.Builder that the HAS can use to * initialize their HTTP / HTTPS server. * * @param conf the HAS config * @param httpAddr the InetSocketAddress of http * @param httpsAddr the InetSocketAddress of https * @param name the host name * @return HttpServer2.Builder the builder * @throws HasException HAS exception */ public HttpServer2.Builder httpServerTemplateForHAS( HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name) throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); HttpServer2.Builder builder = new HttpServer2.Builder().setName(name); if (policy.isHttpEnabled()) { if (httpAddr != null && httpAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } if (policy.isHttpsEnabled() && httpsAddr != null) { HasConfig sslConf = loadSslConfiguration(conf); loadSslConfToHttpServerBuilder(builder, sslConf); if (httpsAddr != null && httpsAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } return builder; } /** * Load HTTPS-related configuration. * * @param conf HAS config * @return HasConfig after loading ssl configuration * @throws HasException HAS exception when loading HTTPS related configuration */ public HasConfig loadSslConfiguration(HasConfig conf) throws HasException { HasConfig sslConf = new HasConfig(); String sslConfigString = conf.getString( WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT); LOG.info("Get the ssl config file: " + sslConfigString); File sslConfig = new File(sslConfigString); if (!sslConfig.exists()) { throw new HasException("The ssl server config file " + sslConfigString + " does not exist."); } try { sslConf.addIniConfig(sslConfig); } catch (IOException e) { throw new HasException("Errors occurred when adding config. " + e.getMessage()); } final String[] reqSslProps = { WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY }; // Check if the required properties are included for (String sslProp : reqSslProps) { if (sslConf.getString(sslProp) == null) { LOG.warn("SSL config " + sslProp + " is missing. If " + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY + " is specified, make sure it is a relative path"); } } boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT); sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth); return sslConf; } public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder, HasConfig sslConf) { return builder .needsClientAuth( sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT)) .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY)) .keyStore(sslConf.getString("ssl.server.keystore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.keystore.type", "jks")) .trustStore(sslConf.getString("ssl.server.truststore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.truststore.type", "jks")) .excludeCiphers( sslConf.getString("ssl.server.exclude.cipher.list")); } /** * Leverages the Configuration.getPassword method to attempt to get * passwords from the CredentialProvider API before falling back to * clear text in config - if falling back is allowed. * * @param conf Configuration instance * @param alias name of the credential to retreive * @return String credential value or null */ public String getPassword(HasConfig conf, String alias) { return conf.getString(alias); } public void stop() throws Exception { if (httpServer != null) { httpServer.stop(); } } public InetSocketAddress getHttpAddress() { return httpAddress; } public InetSocketAddress getHttpsAddress() { return httpsAddress; } } |
blob | Long method2 Feature envy3 Duplicate code4 Inconsistent indentation 5 Undescriptive name for variables 6 Use of public access modifiers for fields7 Use of inline comments 8 Use of Magic numbers (eg 0) 9 Use of hard-coded strings | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent indentation 5. Undescriptive name for variables 6. Use of public access modifiers for fields7. Use of inline comments 8. Use of Magic numbers (e.g. 0) 9. Use of hard-coded strings | blob | 0 | 11427 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java/#L43-L374 | 2 | 1600 | 11427 | major |
| 669 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 6552 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 1 | 669 | 6552 | minor |
| 1028 | { "answer": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Long Method, 2. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | the bad smells are: 1. long method, 2. blob | t | t | f | the bad smells are: 1. long method, 2. blob | feature envy | 0 | 9371 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1028 | 9371 | minor |
| 2189 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13450 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 2 | 2189 | 13450 | minor |
| 1082 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSystemFactoryBean implements InitializingBean, DisposableBean, FactoryBean { private FileSystem fs; private Configuration configuration; private URI uri; private String user; private boolean closeAll = false; private boolean close = true; public void afterPropertiesSet() throws Exception { Configuration cfg = (configuration != null ? configuration : new Configuration(true)); if (uri == null) { uri = FileSystem.getDefaultUri(cfg); } if (StringUtils.hasText(user)) { fs = FileSystem.get(uri, cfg, user); } else { fs = FileSystem.get(uri, cfg); } } public void destroy() throws Exception { if (fs != null && close) { fs.close(); } fs = null; if (closeAll) { // TODO: potentially call close all just for the current user FileSystem.closeAll(); } } public FileSystem getObject() throws Exception { return fs; } public Class getObjectType() { return (fs != null ? fs.getClass() : FileSystem.class); } public boolean isSingleton() { return true; } /** * Sets the Hadoop configuration for this file system. * * @param configuration The configuration to set. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Sets the URI (if available) for this file system. * * @param uri The uri to set. */ public void setUri(URI uri) { this.uri = uri; } /** * Sets the user impersonation (optional) for creating this file-system. * Should be used when running against a Hadoop Kerberos cluster. * * @param user user/group information */ public void setUser(String user) { this.user = user; } /** * Indicates whether all the Hadoop file systems should be closed once this factory is destroyed. * False by default - should be turned on as a safety measure when the app controls the entire lifecycle of Hadoop inside * a JVM. * * @param closeAll the close all * @see FileSystem#closeAll() */ public void setCloseAll(boolean closeAll) { this.closeAll = closeAll; } /** * Indicates whether the Hadoop file systems should be closed once this factory is destroyed. * True by default - should be turned off when running 'embedded' or if long running operations outlive the application context. * * @param close close * @see FileSystem#close() */ public void setClose(boolean close) { this.close = close; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9684 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-hadoop-core/src/main/java/org/springframework/data/hadoop/fs/FileSystemFactoryBean.java/#L34-L131 | 2 | 1082 | 9684 | minor |
| 559 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuckAddDependencyIntention extends BaseIntentionAction { private static Logger LOGGER = Logger.getInstance(BuckAddDependencyIntention.class); /** * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the * given reference element to those of the given psiClass. * * Note that this intention can fail to be created if either side of the edge cannot be * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking * this intention may fail to create edges in either the Buck target graph or the IntelliJ module * graph (or both). */ @Nullable public static BuckAddDependencyIntention create( PsiJavaCodeReferenceElement referenceElement, PsiClass psiClass) { VirtualFile editSourceFile = referenceElement.getContainingFile().getVirtualFile(); if (editSourceFile == null) { return null; } Project project = referenceElement.getProject(); BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); VirtualFile editBuildFile = buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null); if (editBuildFile == null) { return null; } VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile(); if (importSourceFile == null) { return null; } VirtualFile importBuildFile = buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null); if (importBuildFile == null) { return null; } if (importBuildFile.equals(editBuildFile)) { return null; } ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); Module editModule = projectFileIndex.getModuleForFile(editSourceFile); if (editModule == null) { return null; } Module importModule = projectFileIndex.getModuleForFile(importSourceFile); if (importModule == null) { return null; } BuckTarget editSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(editSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (editSourceTarget == null) { return null; } BuckTarget importSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(importSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (importSourceTarget == null) { return null; } return new BuckAddDependencyIntention( project, referenceElement, editBuildFile, editSourceFile, editSourceTarget, editModule, psiClass, importBuildFile, importSourceFile, importSourceTarget, importModule); } private Project project; // Fields pertaining to the element in the file being edited private PsiJavaCodeReferenceElement referenceElement; private VirtualFile editBuildFile; private VirtualFile editSourceFile; private BuckTarget editSourceTarget; private BuckTarget editTarget; private Module editModule; // Fields pertaining to the dependency that should be resolved/imported private PsiClass psiClass; private VirtualFile importBuildFile; private VirtualFile importSourceFile; private BuckTarget importSourceTarget; private BuckTarget importTarget; private Module importModule; BuckAddDependencyIntention( Project project, PsiJavaCodeReferenceElement referenceElement, VirtualFile editBuildFile, VirtualFile editSourceFile, BuckTarget editSourceTarget, Module editModule, PsiClass psiClass, VirtualFile importBuildFile, VirtualFile importSourceFile, BuckTarget importSourceTarget, Module importModule) { this.project = project; this.referenceElement = referenceElement; this.editBuildFile = editBuildFile; this.editSourceFile = editSourceFile; this.editSourceTarget = editSourceTarget; this.editModule = editModule; this.psiClass = psiClass; this.importBuildFile = importBuildFile; this.importSourceFile = importSourceFile; this.importSourceTarget = importSourceTarget; this.importModule = importModule; String message = "Add BUCK dependency on owner(" + importSourceTarget + ")"; setText(message); } @Nls(capitalization = Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return this.getClass().getSimpleName(); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { String msg = "Invoked for project " + project.getName() + " and file " + psiFile.getName(); LOGGER.info(msg); queryBuckForTargets(editor); } /** Helper class to handle deserialization of buck query. */ static class TargetMetadata { public BuckTarget target; public @Nullable List deps; public @Nullable List visibility; // null means PUBLIC public @Nullable List srcs; public @Nullable List resources; static TargetMetadata from( BuckTargetLocator buckTargetLocator, BuckTarget target, JsonObject payload) { TargetMetadata targetMetadata = new TargetMetadata(); targetMetadata.target = target; targetMetadata.srcs = stringListOrNull(payload.get("srcs")); targetMetadata.resources = stringListOrNull(payload.get("resources")); // Deps are a list of BuckTargets targetMetadata.deps = Optional.ofNullable(stringListOrNull(payload.get("deps"))) .map( deps -> deps.stream() .map( s -> BuckTarget.parse(s).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList())) .orElse(null); // Visibilility falls in one of three cases: // (1) if unspecified => means visibility is limited to the current package // (2) contains "PUBLIC" => available everywhere // (3) otherwise is a list of buck target patterns where it is visible List optionalVisibility = stringListOrNull(payload.get("visibility")); if (optionalVisibility == null) { targetMetadata.visibility = Collections.singletonList(target.asPattern().asPackageMatchingPattern()); } else if (optionalVisibility.contains("PUBLIC")) { targetMetadata.visibility = null; // } else { targetMetadata.visibility = optionalVisibility .stream() .map(p -> BuckTargetPattern.parse(p).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList()); } return targetMetadata; } static @Nullable List stringListOrNull(@Nullable JsonElement jsonElement) { if (jsonElement == null) { return null; } return new Gson().fromJson(jsonElement, new TypeToken>() {}.getType()); } boolean isVisibleTo(BuckTarget target) { if (visibility == null) { return true; } return visibility.stream().anyMatch(pattern -> pattern.matches(target)); } boolean hasDependencyOn(BuckTarget target) { return deps.stream().anyMatch(dep -> dep.equals(target)); } boolean contains(BuckTarget targetFile) { if (!target.asPattern().asPackageMatchingPattern().matches(targetFile)) { return false; } String relativeToBuildFile = targetFile.getRuleName(); return srcs.contains(relativeToBuildFile) || resources.contains(relativeToBuildFile); } } /** Queries buck for targets that own the editSourceFile and the importSourceFile. */ private void queryBuckForTargets(Editor editor) { BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); String editPath = editSourceFile.getPath(); String importPath = importSourceFile.getPath(); BuckJsonCommandHandler> handler = new BuckJsonCommandHandler<>( project, BuckCommand.QUERY, new Callback>() { @Override public List deserialize(JsonElement jsonElement) throws IOException { Type type = new TypeToken>() {}.getType(); Map raw = new Gson().fromJson(jsonElement, type); List results = new ArrayList<>(); for (Entry entry : raw.entrySet()) { BuckTarget.parse(entry.getKey()) .map(buckTargetLocator::resolve) .map( target -> TargetMetadata.from(buckTargetLocator, target, entry.getValue())) .ifPresent(results::add); } return results; } @Override public void onSuccess(List results, String stderr) { List editTargets = new ArrayList<>(); List importTargets = new ArrayList<>(); for (TargetMetadata targetMetadata : results) { if (targetMetadata.contains(editSourceTarget)) { editTargets.add(targetMetadata); } if (targetMetadata.contains(importSourceTarget)) { importTargets.add(targetMetadata); } } updateDependencies(editor, editTargets, importTargets); } @Override public void onFailure( String stdout, String stderr, @Nullable Integer exitCode, @Nullable Throwable throwable) { BuckNotification.getInstance(project) .showWarningBalloon( "Could not determine owners for " + editSourceFile + " and/or " + importSourceFile); return; } }); handler .command() .addParameters( "owner(%s)", editPath, importPath, "--output-attributes=deps|srcs|visibility|resources"); handler.runInCurrentThreadPostEnd(() -> {}); } /** * Implementation of {@link * com.intellij.notification.NotificationListener#hyperlinkUpdate(Notification, HyperlinkEvent)}. */ private void hyperlinkActivated( @NotNull Notification notification, @NotNull HyperlinkEvent event) { String href = event.getDescription(); switch (href) { case "editTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(editTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "editBuildFile": FileEditorManager.getInstance(project).openFile(editBuildFile, true); break; case "editSourceFile": FileEditorManager.getInstance(project).openFile(editSourceFile, true); break; case "importTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(importTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "importBuildFile": FileEditorManager.getInstance(project).openFile(importBuildFile, true); break; case "importSourceFile": FileEditorManager.getInstance(project).openFile(importSourceFile, true); break; } } private void updateDependencies( Editor editor, List editTargets, List importTargets) { if (editTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + editSourceTarget + " in " + editBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (importTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + importSourceTarget + " in " + importBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } TargetMetadata editTargetMetadata = editTargets.get(0); TargetMetadata importTargetMetadata = importTargets.get(0); editTarget = editTargetMetadata.target; importTarget = importTargetMetadata.target; if (!importTargetMetadata.isVisibleTo(editTarget)) { String message = "Add dependency failed: The target " + importTarget + " is not visible to " + editTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (!editTargetMetadata.hasDependencyOn(importTarget)) { if (!BuckDeps.modifyTargetToAddDependency( editBuildFile, editTarget.toString(), importTarget.toString())) { String message = "Add dependency failed: Could not add modify build file for " + editTarget + " to add dependency on " + importTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } } else { String message = "No need to modify build file " + editBuildFile + ", already has dependency from " + editTarget + " to " + importTarget + ""; BuckNotification.getInstance(project).showInfoBalloon(message, this::hyperlinkActivated); } ModuleRootModificationUtil.updateModel( editModule, (modifiableRootModel -> { if (modifiableRootModel.findModuleOrderEntry(importModule) != null) { LOGGER.info( "No need to modify module " + editModule.getName() + ", already has dependency on " + importModule.getName()); } else { modifiableRootModel.addModuleOrderEntry(importModule); LOGGER.info( "Successfully added module dependency from " + editModule.getName() + " on " + importModule.getName()); } new AddImportAction(project, referenceElement, editor, psiClass).execute(); })); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 5627 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/autodeps/BuckAddDependencyIntention.java/#L66-L480 | 1 | 559 | 5627 | major |
| 1052 | YES, I found bad smells the bad smells are: 1. Empty default constructor 2. Lack of encapsulation and direct manipulation of private data fields through getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | Empty default constructor2 Lack of encapsulation and direct manipulation of private data fields through getters and setters | t | f | f | . Empty default constructor2. Lack of encapsulation and direct manipulation of private data fields through getters and setters | data class | 0 | 9479 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 2 | 1052 | 9479 | minor |
| 1067 | YES I found bad smells The bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 9582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1067 | 9582 | minor |
| 2240 | {"response": "YES I found bad smells", "bad smells are:": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 13619 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 | 2 | 2240 | 13619 | major |
| 941 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setContentLength(final int length) { setIntHeader("Content-Length", length); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 8463 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockHttpServletResponse.java/#L613-L617 | 1 | 941 | 8463 | minor |
| 2206 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | long method | t | t | f | long method | blob | 0 | 13513 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 1 | 2206 | 13513 | major |
| 739 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class CancelableThread extends Thread { protected boolean running = true; protected boolean canceled = false; public synchronized final boolean isRunning() { return running; } public synchronized final void setRunning(boolean running) { this.running = running; } /** * Subclasses shouldn't do any potentially conflicting UI work before * checking to see if the thread has been canceled. */ public synchronized final boolean isCanceled() { return canceled; } public synchronized final void cancel() { this.canceled = true; } /** * Cancels the thread given if it's running. */ public static void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized ( thread ) { if ( thread.isRunning() ) { thread.cancel(); } } } } } |
data class | f | f | f | data class | 0 | 6968 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/CancelableThread.java/#L23-L61 | 2 | 739 | 6968 | minor | ||
| 892 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8106 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 1 | 892 | 8106 | minor |
| 3787 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 9539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 3787 | 9539 | minor |
| 1563 | {"response": "YES I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | t | f | f | data class | 0 | 11316 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 1563 | 11316 | minor | ||
| 1569 | {"answer": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
blob | data class | t | t | f | data class | blob | 0 | 11334 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 1569 | 11334 | major |
| 330 | { "NO, I did not find any bad smell" : "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WantPropertyElement extends Frame implements WantsObjectFrameI, HasSubjectFrameI { int liCounter = 1; ANode predicate; ANode object; ANode reify; boolean objectIsBlank = false; public WantPropertyElement(HasSubjectFrameI s, AbsXMLContext x) { super(s, x); } // These three are used as bitfields static final private int TYPEDLITERAL = 1; static final private int EMPTYWITHOBJ = 2; static final private int PARSETYPE = 4; @Override public FrameI startElement(String uri, String localName, String rawName, Attributes atts) throws SAXParseException { clearObject(); if (nonWhiteMsgGiven) taint.isTainted(); nonWhiteMsgGiven = false; if (uri==null || uri.equals("")) { warning(WARN_UNQUALIFIED_ELEMENT,"Unqualified property elements are not allowed. Treated as a relative URI."); } ElementLexer el = new ElementLexer(taint, this, uri, localName, rawName, E_LI, CoreAndOldTerms | E_DESCRIPTION, false); // if (el.badMatch) // warning(ERR_SYNTAX_ERROR,"bad use of " + rawName); predicate = el.goodMatch ? (AResourceInternal) rdf_n(liCounter++) : URIReference.fromQName(this, uri, localName); if (taint.isTainted()) predicate.taint(); taint = new TaintImpl(); AttributeLexer ap = new AttributeLexer(this, // xml: A_XMLLANG | A_XMLBASE | A_XML_OTHER // legal rdf: | A_DATATYPE | A_ID | A_NODEID | A_PARSETYPE | A_RESOURCE | A_TYPE, // bad rdf: A_BADATTRS); int cnt = ap.processSpecials(taint, atts); // These three states are intended as mutually // incompatible, but all three can occur // together. Any two of the three, or all // three is a syntax errror. // Having none of these is legal. final int nextStateCode = (ap.datatype == null ? 0 : TYPEDLITERAL) | (ap.parseType == null ? 0 : PARSETYPE) | (mustBeEmpty(ap, atts, cnt) ? EMPTYWITHOBJ : 0); if (this.badStateCode(nextStateCode)) { warning(errorNumber(nextStateCode), descriptionOfCases(ap, nextStateCode, propertyAttributeDescription(atts, ap, cnt))); } AbsXMLContext x = ap.xml(xml); reify = ap.id == null ? null : URIReference.fromID(this, x, ap.id); if (taint.isTainted()) predicate.taint(); if (mustBeEmpty(ap, atts, cnt)) { if (ap.nodeID != null) { object = new ARPResource(arp, ap.nodeID); checkNodeID_XMLName(object, ap.nodeID); objectIsBlank = true; } if (ap.resource != null) { if (object != null) { if (!badStateCode(nextStateCode)) // otherwise warning already given warning(ERR_SYNTAX_ERROR, "On a property element, only one of the attributes rdf:nodeID or rdf:resource is permitted."); } else object = URIReference.resolve(this, x, ap.resource); } if (object == null) { object = new ARPResource(arp); objectIsBlank = true; } if (taint.isTainted()) object.taint(); processPropertyAttributes(ap, atts, x); } FrameI nextFrame = nextFrame(atts, ap, cnt, nextStateCode, x); if (object != null) { if (taint.isTainted()) object.taint(); theObject(object); } if (taint.isTainted()) predicate.taint(); return nextFrame; } private boolean mustBeEmpty(AttributeLexer ap, Attributes atts, int cnt) { return cnt < atts.getLength() || ap.type != null || ap.nodeID != null || ap.resource != null; } private FrameI nextFrame(Attributes atts, AttributeLexer ap, int cnt, int nextStateCode, AbsXMLContext x) throws SAXParseException { switch (nextStateCode) { case 0: return new WantLiteralValueOrDescription(this, x); case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case PARSETYPE: return withParsetype(ap.parseType, x); case TYPEDLITERAL | EMPTYWITHOBJ: case TYPEDLITERAL: return new WantTypedLiteral(this, ap.datatype, x); case EMPTYWITHOBJ: return new WantEmpty(this, x); } throw new IllegalStateException("impossible"); } private FrameI withParsetype(String pt, AbsXMLContext x) throws SAXParseException { if (pt.equals("Collection")) { return new RDFCollection(this, x); } if (pt.equals("Resource")) { if (object == null) { // in some error cases the object has already been set. object = new ARPResource(arp); objectIsBlank = true; } return new WantPropertyElement(this, x); } if (!pt.equals("Literal")) { warning(WARN_UNKNOWN_PARSETYPE, "Unknown rdf:parseType: '" + pt + "' (treated as 'Literal'."); } return new OuterXMLLiteral(this, x, pt); } @Override String suggestParsetypeLiteral() { return (getParent() instanceof WantTopLevelDescription) ? "" : super .suggestParsetypeLiteral(); } @Override public void aPredAndObj(ANode p, ANode o) { triple(object, p, o); } @Override public void makeSubjectReificationWith(ANode r) { triple(r, RDF_SUBJECT, object); } @Override public void theObject(ANode o) { HasSubjectFrameI p = (HasSubjectFrameI) getParent(); p.aPredAndObj(predicate, o); if (reify != null) { triple(reify, RDF_TYPE, RDF_STATEMENT); triple(reify, RDF_OBJECT, o); triple(reify, RDF_PREDICATE, predicate); p.makeSubjectReificationWith(reify); } } @Override public void endElement() { clearObject(); } @Override public void abort() { clearObject(); } private void clearObject() { if (objectIsBlank) arp.endLocalScope(object); objectIsBlank = false; object = null; } static private URIReference _rdf_n[] = new URIReference[0]; static private URIReference rdf_n(int i) { if (i >= _rdf_n.length) { int newLength = (i + 10) * 3 / 2; URIReference new_rdf_n[] = new URIReference[newLength]; System.arraycopy(_rdf_n, 0, new_rdf_n, 0, _rdf_n.length); for (int j = _rdf_n.length; j < newLength; j++) { new_rdf_n[j] = URIReference.createNoChecks(rdfns + "_" + j); } _rdf_n = new_rdf_n; } return _rdf_n[i]; } /*************************************************************************** * * ERROR HANDLING CODE * **************************************************************************/ // Error detection private boolean badStateCode(int nextStateCode) { switch (nextStateCode) { case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case TYPEDLITERAL | EMPTYWITHOBJ: return true; case 0: case PARSETYPE: case TYPEDLITERAL: case EMPTYWITHOBJ: return false; } throw new IllegalStateException("impossible"); } // Error classification private int errorNumber(int nextStateCode) { // TODO: not for 2.3. refine this error code. return ERR_SYNTAX_ERROR; } /*************************************************************************** * * ERROR MESSAGES * **************************************************************************/ private String descriptionOfCases(AttributeLexer ap, int nextStateCode, String propAttrs) { return ((propAttrs == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && propAttrs == null)) ? pairwiseIncompatibleErrorMessage( nextStateCode, ap, propAttrs) : complicatedErrorMessage(nextStateCode, ap, propAttrs); } private String pairwiseIncompatibleErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { ArrayList cases = new ArrayList<>(); if ((nextStateCode & PARSETYPE) != 0) cases.add("rdf:parseType"); if ((nextStateCode & TYPEDLITERAL) != 0) cases.add("rdf:datatype"); if (ap.nodeID != null) cases.add("rdf:nodeID"); if (ap.resource != null) cases.add("rdf:resource"); if (ap.type != null) cases.add("rdf:type"); if (cases.size() == 1) { if (propAttrs == null) throw new IllegalStateException("Shouldn't happen."); return "The attribute " + cases.get(0) + " is not permitted with " + propAttrs + " on a property element."; } String rslt = "On a property element, only one of the "; if (propAttrs == null) rslt += "attributes "; for (int i = 0; i < cases.size(); i++) { rslt += cases.get(i); switch (cases.size() - i) { case 1: break; case 2: rslt += " or "; break; default: rslt += ", "; break; } } if (propAttrs != null) { rslt += " attributes or " + propAttrs; } rslt += " is permitted."; return rslt; } private String complicatedErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { String subjectIs; if (ap.nodeID == null && ap.resource == null && (ap.type == null || propAttrs == null)) throw new IllegalStateException("precondition failed."); switch (nextStateCode & (TYPEDLITERAL | PARSETYPE)) { case TYPEDLITERAL | PARSETYPE: subjectIs = "the mutually incompatible attributes rdf:datatype and rdf:parseType are"; break; case TYPEDLITERAL: subjectIs = "the attribute rdf:datatype is"; break; case PARSETYPE: subjectIs = "the attribute rdf:parseType is"; break; default: throw new IllegalStateException("precondition failed"); } String nodeIDResource = null; if (ap.nodeID != null && ap.resource != null) { nodeIDResource = "the mutually incompatible attributes rdf:nodeID and rdf:resource"; } else if (ap.nodeID != null) { nodeIDResource = "the attribute rdf:nodeID"; } else if (ap.resource != null) { nodeIDResource = "the attribute rdf:resource"; } int otherAttCount = nodeIDResource == null ? 0 : 1; String otherAtts; if (ap.type != null) otherAttCount++; if (propAttrs != null) otherAttCount++; if (otherAttCount < 2) throw new IllegalStateException("logic error"); otherAtts = otherAttCount == 2 ? "both " : "each of "; if (ap.type != null && propAttrs != null) { if (nodeIDResource == null) otherAtts += "the attribute rdf:type and the " + propAttrs; else otherAtts += "the attribute rdf:type, the " + propAttrs; } else if (ap.type != null) { otherAtts += "the attribute rdf:type"; } else { otherAtts = "the " + propAttrs; } if (nodeIDResource != null) otherAtts += " and "+nodeIDResource; return "On a property element, " + subjectIs + " incompatible with " + otherAtts +"."; } private String propertyAttributeDescription(Attributes atts, AttributeLexer ap, int cnt) { String propAttrs = ""; int propAttrCount = atts.getLength() - cnt; int found = 0; if (propAttrCount == 0) return null; switch (propAttrCount) { case 0: break; case 1: case 2: case 3: for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { propAttrs += atts.getQName(i); found++; switch (propAttrCount - found) { case 0: break; case 1: propAttrs += " and "; break; default: propAttrs += ", "; } } break; default: if (propAttrCount < 0) throw new IllegalStateException("Shouldn't happen."); for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { found++; switch (found) { case 1: propAttrs += atts.getQName(i) + ", "; break; case 2: propAttrs += atts.getQName(i) + ", ..."; break; default: // ignore } } } return "property attributes (" + propAttrs + ")"; } } |
blob | t | f | f | blob | 0 | 3390 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/states/WantPropertyElement.java/#L27-L436 | 1 | 330 | 3390 | minor | ||
| 1108 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TableAliasImpl extends SQLSyntaxElementBase implements TableAlias { private final String _tableAlias; private final ColumnNameList _columnAliases; public TableAliasImpl( SQLProcessorAggregator processor, String tableAlias, ColumnNameList columnNames ) { this( processor, TableAlias.class, tableAlias, columnNames ); } protected TableAliasImpl( SQLProcessorAggregator processor, Class implementingClass, String tableAlias, ColumnNameList columnNames ) { super( processor, implementingClass ); Objects.requireNonNull( tableAlias, "table alias table name" ); this._tableAlias = tableAlias; this._columnAliases = columnNames; } public ColumnNameList getColumnAliases() { return this._columnAliases; } public String getTableAlias() { return this._tableAlias; } @Override protected boolean doesEqual( TableAlias another ) { return this._tableAlias.equals( another.getTableAlias() ) && bothNullOrEquals( this._columnAliases, another.getColumnAliases() ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9882 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/grammar/query/TableAliasImpl.java/#L31-L68 | 2 | 1108 | 9882 | minor |
| 542 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5540 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 542 | 5540 | minor |
| 384 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3921 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 384 | 3921 | major |
| 1645 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LogUtils { private static final String HIVE_L4J = "metastore-log4j2.properties"; private static final Logger l4j = LoggerFactory.getLogger(LogUtils.class); @SuppressWarnings("serial") public static class LogInitializationException extends Exception { LogInitializationException(String msg) { super(msg); } } /** * This is an exception that can be passed to logger just for printing the stacktrace. */ public static class StackTraceLogger extends Exception { public StackTraceLogger(final String msg) { super(msg); } } /** * Initialize log4j. * * @return an message suitable for display to the user * @throws LogInitializationException if log4j fails to initialize correctly */ public static String initHiveLog4j(Configuration conf) throws LogInitializationException { return initHiveLog4jCommon(conf, MetastoreConf.ConfVars.LOG4J_FILE); } private static String initHiveLog4jCommon(Configuration conf, ConfVars confVarName) throws LogInitializationException { if (MetastoreConf.getVar(conf, confVarName).equals("")) { // if log4j configuration file not set, or could not found, use default setting return initHiveLog4jDefault(conf, "", confVarName); } else { // if log4j configuration file found successfully, use HiveConf property value String log4jFileName = MetastoreConf.getVar(conf, confVarName); File log4jConfigFile = new File(log4jFileName); boolean fileExists = log4jConfigFile.exists(); if (!fileExists) { // if property specified file not found in local file system // use default setting return initHiveLog4jDefault( conf, "Not able to find conf file: " + log4jConfigFile, confVarName); } else { // property speficied file found in local file system // use the specified file final boolean async = checkAndSetAsyncLogging(conf); // required for MDC based routing appender so that child threads can inherit the MDC context System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, log4jFileName); logConfigLocation(); return "Logging initialized using configuration in " + log4jConfigFile + " Async: " + async; } } } private static boolean checkAndSetAsyncLogging(final Configuration conf) { final boolean asyncLogging = MetastoreConf.getBoolVar(conf, ConfVars.ASYNC_LOG_ENABLED); if (asyncLogging) { System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); // default is ClassLoaderContextSelector which is created during automatic logging // initialization in a static initialization block. // Changing ContextSelector at runtime requires creating new context factory which will // internally create new context selector based on system property. LogManager.setFactory(new Log4jContextFactory()); } return asyncLogging; } private static String initHiveLog4jDefault(Configuration conf, String logMessage, ConfVars confVarName) throws LogInitializationException { URL hive_l4j = null; switch (confVarName) { case LOG4J_FILE: hive_l4j = LogUtils.class.getClassLoader().getResource(HIVE_L4J); break; default: break; } if (hive_l4j != null) { final boolean async = checkAndSetAsyncLogging(conf); System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, hive_l4j.toString()); logConfigLocation(); return (logMessage + "\n" + "Logging initialized using configuration in " + hive_l4j + " Async: " + async); } else { throw new LogInitializationException( logMessage + "Unable to initialize logging using " + LogUtils.HIVE_L4J + ", not found on CLASSPATH!"); } } private static void logConfigLocation() throws LogInitializationException { // Log a warning if hive-default.xml is found on the classpath if (MetastoreConf.getHiveDefaultLocation() != null) { l4j.warn("DEPRECATED: Ignoring hive-default.xml found on the CLASSPATH at " + MetastoreConf.getHiveDefaultLocation().getPath()); } // Look for hive-site.xml on the CLASSPATH and log its location if found. if (MetastoreConf.getHiveSiteLocation() == null) { l4j.warn("hive-site.xml not found on CLASSPATH"); } else { l4j.debug("Using hive-site.xml found on CLASSPATH at " + MetastoreConf.getHiveSiteLocation().getPath()); } } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 11560 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/LogUtils.java/#L37-L149 | 1 | 1645 | 11560 | minor |
| 2549 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | "YES I found bad smells", "bad smells are" | t | f | f | "YES I found bad smells", "bad smells are" | blob | 0 | 14794 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 2549 | 14794 | minor |
| 735 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6908 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 735 | 6908 | minor |
| 150 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1904 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 150 | 1904 | major |
| 749 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({"unchecked", "rawtypes"}) public final class None extends Option { private static final None INSTANCE = new None<>(); /** * Get the static instance. * @param The type of this no-value object. * @return the static instance */ public static final None getInstance() { return INSTANCE; } /** * Default constructor, does nothing. */ public None() { // super(null); // no-op } @Override public boolean hasValue() { return false; } @Override public T getValue() { throw new NoSuchElementException("None does not contain a value"); } @Override public String toString() { return "None()"; } @Override public boolean equals(Object other) { return (other == null || other.getClass() != None.class) ? false : true; } @Override public int hashCode() { return -31; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7022 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/core/src/org/apache/pivot/functional/monad/None.java/#L24-L70 | 2 | 749 | 7022 | minor |
| 554 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy 2 Long method | t | f | f | . Feature envy 2. Long method. | data class | 0 | 5603 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 554 | 5603 | major |
| 476 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4588 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 476 | 4588 | minor |
| 1802 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 12020 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 1802 | 12020 | major |
| 1569 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11334 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 1569 | 11334 | major |
| 1215 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | blob, data class | t | t | f | blob, data class | long method | 0 | 10318 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 1215 | 10318 | minor |
| 616 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6180 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 2 | 616 | 6180 | minor |
| 1728 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | t | f | f | feature envy | 0 | 11811 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 1728 | 11811 | minor | ||
| 1690 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic number, 5. Intimacy inversion, 6. Lazy class, 7. Data clump. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic number, 5 Intimacy inversion, 6 Lazy class, 7 Data clump | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic number, 5. Intimacy inversion, 6. Lazy class, 7. Data clump. | blob | 0 | 11702 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 2 | 1690 | 11702 | minor |
| 2668 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | data class | t | t | f | data class | blob | 0 | 15207 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 1 | 2668 | 15207 | minor |
| 3763 | {"response": "YES, I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CurrentCreationalContext { private final ThreadLocal> creationalContext = new ThreadLocal>(); public CreationalContext get() { return creationalContext.get(); } public void set(CreationalContext value) { creationalContext.set(value); } public void remove() { creationalContext.remove(); } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 9405 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/cdi/CurrentCreationalContext.java/#L24-L38 | 1 | 3763 | 9405 | minor |
| 2174 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Long parameter list", "Feature envy", "Data class", "Message chains", "Long class" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | long method, long parameter list, feature envy, data class, message chains, long class | t | t | f | long method, long parameter list, feature envy, data class, message chains, long class | blob | 0 | 13387 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 2 | 2174 | 13387 | minor |
| 1159 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10159 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 2 | 1159 | 10159 | minor |
| 1591 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupByMergingQueryRunnerV2 implements QueryRunner { private static final Logger log = new Logger(GroupByMergingQueryRunnerV2.class); private static final String CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION = "mergeRunnersUsingChainedExecution"; private final GroupByQueryConfig config; private final Iterable> queryables; private final ListeningExecutorService exec; private final QueryWatcher queryWatcher; private final int concurrencyHint; private final BlockingPool mergeBufferPool; private final ObjectMapper spillMapper; private final String processingTmpDir; private final int mergeBufferSize; public GroupByMergingQueryRunnerV2( GroupByQueryConfig config, ExecutorService exec, QueryWatcher queryWatcher, Iterable> queryables, int concurrencyHint, BlockingPool mergeBufferPool, int mergeBufferSize, ObjectMapper spillMapper, String processingTmpDir ) { this.config = config; this.exec = MoreExecutors.listeningDecorator(exec); this.queryWatcher = queryWatcher; this.queryables = Iterables.unmodifiableIterable(Iterables.filter(queryables, Predicates.notNull())); this.concurrencyHint = concurrencyHint; this.mergeBufferPool = mergeBufferPool; this.spillMapper = spillMapper; this.processingTmpDir = processingTmpDir; this.mergeBufferSize = mergeBufferSize; } @Override public Sequence run(final QueryPlus queryPlus, final Map responseContext) { final GroupByQuery query = (GroupByQuery) queryPlus.getQuery(); final GroupByQueryConfig querySpecificConfig = config.withOverrides(query); // CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION is here because realtime servers use nested mergeRunners calls // (one for the entire query and one for each sink). We only want the outer call to actually do merging with a // merge buffer, otherwise the query will allocate too many merge buffers. This is potentially sub-optimal as it // will involve materializing the results for each sink before starting to feed them into the outer merge buffer. // I'm not sure of a better way to do this without tweaking how realtime servers do queries. final boolean forceChainedExecution = query.getContextBoolean( CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, false ); final QueryPlus queryPlusForRunners = queryPlus .withQuery( query.withOverriddenContext(ImmutableMap.of(CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, true)) ) .withoutThreadUnsafeState(); if (QueryContexts.isBySegment(query) || forceChainedExecution) { ChainedExecutionQueryRunner runner = new ChainedExecutionQueryRunner<>(exec, queryWatcher, queryables); return runner.run(queryPlusForRunners, responseContext); } final boolean isSingleThreaded = querySpecificConfig.isSingleThreaded(); final AggregatorFactory[] combiningAggregatorFactories = new AggregatorFactory[query.getAggregatorSpecs().size()]; for (int i = 0; i < query.getAggregatorSpecs().size(); i++) { combiningAggregatorFactories[i] = query.getAggregatorSpecs().get(i).getCombiningFactory(); } final File temporaryStorageDirectory = new File( processingTmpDir, StringUtils.format("druid-groupBy-%s_%s", UUID.randomUUID(), query.getId()) ); final int priority = QueryContexts.getPriority(query); // Figure out timeoutAt time now, so we can apply the timeout to both the mergeBufferPool.take and the actual // query processing together. final long queryTimeout = QueryContexts.getTimeout(query); final boolean hasTimeout = QueryContexts.hasTimeout(query); final long timeoutAt = System.currentTimeMillis() + queryTimeout; return new BaseSequence<>( new BaseSequence.IteratorMaker>() { @Override public CloseableGrouperIterator make() { final List resources = new ArrayList<>(); try { final LimitedTemporaryStorage temporaryStorage = new LimitedTemporaryStorage( temporaryStorageDirectory, querySpecificConfig.getMaxOnDiskStorage() ); final ReferenceCountingResourceHolder temporaryStorageHolder = ReferenceCountingResourceHolder.fromCloseable(temporaryStorage); resources.add(temporaryStorageHolder); // If parallelCombine is enabled, we need two merge buffers for parallel aggregating and parallel combining final int numMergeBuffers = querySpecificConfig.getNumParallelCombineThreads() > 1 ? 2 : 1; final List> mergeBufferHolders = getMergeBuffersHolder( numMergeBuffers, hasTimeout, timeoutAt ); resources.addAll(mergeBufferHolders); final ReferenceCountingResourceHolder mergeBufferHolder = mergeBufferHolders.get(0); final ReferenceCountingResourceHolder combineBufferHolder = numMergeBuffers == 2 ? mergeBufferHolders.get(1) : null; Pair, Accumulator> pair = RowBasedGrouperHelper.createGrouperAccumulatorPair( query, false, null, config, Suppliers.ofInstance(mergeBufferHolder.get()), combineBufferHolder, concurrencyHint, temporaryStorage, spillMapper, combiningAggregatorFactories, exec, priority, hasTimeout, timeoutAt, mergeBufferSize ); final Grouper grouper = pair.lhs; final Accumulator accumulator = pair.rhs; grouper.init(); final ReferenceCountingResourceHolder> grouperHolder = ReferenceCountingResourceHolder.fromCloseable(grouper); resources.add(grouperHolder); ListenableFuture> futures = Futures.allAsList( Lists.newArrayList( Iterables.transform( queryables, new Function, ListenableFuture>() { @Override public ListenableFuture apply(final QueryRunner input) { if (input == null) { throw new ISE( "Null queryRunner! Looks to be some segment unmapping action happening" ); } ListenableFuture future = exec.submit( new AbstractPrioritizedCallable(priority) { @Override public AggregateResult call() { try ( // These variables are used to close releasers automatically. @SuppressWarnings("unused") Releaser bufferReleaser = mergeBufferHolder.increment(); @SuppressWarnings("unused") Releaser grouperReleaser = grouperHolder.increment() ) { final AggregateResult retVal = input.run(queryPlusForRunners, responseContext) .accumulate( AggregateResult.ok(), accumulator ); // Return true if OK, false if resources were exhausted. return retVal; } catch (QueryInterruptedException e) { throw e; } catch (Exception e) { log.error(e, "Exception with one of the sequences!"); throw new RuntimeException(e); } } } ); if (isSingleThreaded) { waitForFutureCompletion( query, Futures.allAsList(ImmutableList.of(future)), hasTimeout, timeoutAt - System.currentTimeMillis() ); } return future; } } ) ) ); if (!isSingleThreaded) { waitForFutureCompletion(query, futures, hasTimeout, timeoutAt - System.currentTimeMillis()); } return RowBasedGrouperHelper.makeGrouperIterator( grouper, query, new Closeable() { @Override public void close() { for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } } } ); } catch (Throwable e) { // Exception caught while setting up the iterator; release resources. for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } throw e; } } @Override public void cleanup(CloseableGrouperIterator iterFromMake) { iterFromMake.close(); } } ); } private List> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List> mergeBufferHolder; // This will potentially block if there are no merge buffers left in the pool. if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } } private void waitForFutureCompletion( GroupByQuery query, ListenableFuture> future, boolean hasTimeout, long timeout ) { try { if (queryWatcher != null) { queryWatcher.registerQuery(query, future); } if (hasTimeout && timeout <= 0) { throw new TimeoutException(); } final List results = hasTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get(); for (AggregateResult result : results) { if (!result.isOk()) { future.cancel(true); throw new ResourceLimitExceededException(result.getReason()); } } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (CancellationException e) { throw new QueryInterruptedException(e); } catch (TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 11390 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/GroupByMergingQueryRunnerV2.java/#L72-L392 | 2 | 1591 | 11390 | critical |
| 301 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3155 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 301 | 3155 | major |
| 803 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Region { /** * Gets the region and state machine unique id. * * @return the region and state machine unique id */ UUID getUuid(); /** * Gets the region and state machine id. This identifier * is provided for users disposal and can be set from * a various ways to build a machines. * * @return the region and state machine id */ String getId(); /** * Start the region. */ void start(); /** * Stop the region. */ void stop(); /** * Send an event {@code E} wrapped with a {@link Message} to the region. * * @param event the wrapped event to send * @return true if event was accepted */ boolean sendEvent(Message event); /** * Send an event {@code E} to the region. * * @param event the event to send * @return true if event was accepted */ boolean sendEvent(E event); /** * Gets the current {@link State}. * * @return current state */ State getState(); /** * Gets the {@link State}s defined in this region. Returned collection is * an unmodifiable copy because states in a state machine are immutable. * * @return immutable copy of states */ Collection> getStates(); /** * Gets a {@link Transition}s for this region. * * @return immutable copy of transitions */ Collection> getTransitions(); /** * Checks if region complete. Region is considered to be completed if it has * reached its end state and no further event processing is happening. * * @return true, if complete */ boolean isComplete(); /** * Adds the state listener. * * @param listener the listener */ void addStateListener(StateMachineListener listener); /** * Removes the state listener. * * @param listener the listener */ void removeStateListener(StateMachineListener listener); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7611 | https://github.com/spring-projects/spring-statemachine/blob/02ecb28751fcffd6f5306189f41bbcadcd3af18a/spring-statemachine-core/src/main/java/org/springframework/statemachine/region/Region.java/#L35-L123 | 2 | 803 | 7611 | major |
| 617 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } } |
blob | 1. data class, 2. long method | t | t | f | 1. data class, 2. long method | blob | 0 | 6181 | https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 | 1 | 617 | 6181 | minor |
| 2087 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Use of unneeded comments 6. Too many parameters in constructor 7. Use of field setters instead of encapsulation 8. Not following object-oriented principles (e.g. workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class) 9. Poor exception handling 10. Lack of cohesion (class is responsible for both writing and setting fields) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | Long method2 Feature envy3 Duplicate code4 Inconsistent naming conventions5 Use of unneeded comments6 Too many parameters in constructor7 Use of field setters instead of encapsulation8 Not following object-oriented principles (eg workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class)9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent naming conventions5. Use of unneeded comments6. Too many parameters in constructor7. Use of field setters instead of encapsulation8. Not following object-oriented principles (e.g. workspaceName and workspaceOwner should be in a separate class instead of individual fields in this class)9. Poor exception handling | data class | 0 | 13106 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 2 | 2087 | 13106 | major |
| 809 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7647 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 | 2 | 809 | 7647 | minor |
| 678 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicated code 3. Feature envy 4. Long constructor 5. Temporal coupling 6. Incomplete abstraction 7. Magic numbers 8. Primitive obsession 9. Complex conditional logic 10. Data clumps 11. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
data class | Long method2 Duplicated code3 Feature envy4 Long constructor5 Temporal coupling6 Incomplete abstraction7 Magic numbers8 Primitive obsession9 Complex conditional logic | t | f | f | . Long method2. Duplicated code3. Feature envy4. Long constructor5. Temporal coupling6. Incomplete abstraction7. Magic numbers8. Primitive obsession9. Complex conditional logic | data class | 0 | 6584 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 2 | 678 | 6584 | minor |
| 1288 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10614 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1288 | 10614 | minor |
| 1481 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11082 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 2 | 1481 | 11082 | minor |
| 4109 | opens = new Open[count]; YES I found bad smells. The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 10822 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 4109 | 10822 | major |
| 312 | {"response": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onNodeSelected(TreeNodeElement node, SignalEvent event) { getSelectionModel().setTreeActive(true); selectNode(node.getData(), event, true); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3213 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/tree/Tree.java/#L732-L736 | 1 | 312 | 3213 | critical |
| 3947 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10329 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 3947 | 10329 | major |
| 926 | {"message":"YES, I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 8312 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 926 | 8312 | critical |
| 1095 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
feature envy | the bad smells are: long method, data class | t | t | f | the bad smells are: long method, data class | feature envy | 0 | 9781 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 1 | 1095 | 9781 | major |
| 1804 | YES I found bad smells the bad smells are: 1. Long method 2. Complicated code structure 3. Lack of comments or documentation 4. Poor variable naming (e.g. "builder", "pos", etc.) 5. Magic numbers or string literals used in the code 6. Use of nested loops 7. Use of enums in a non-idiomatic way 8. Lack of unit tests 9. Violation of single responsibility principle (e.g. static initializer and multiple methods in the same class) 10. Inconsistent naming conventions (e.g. "JODA_HALFDAY" vs "POSTGRES_HALFDAY_AM") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } } |
blob | Long method2 Complicated code structure3 Lack of comments or documentation4 Poor variable naming (eg "builder", "pos", etc)5 Magic numbers or string literals used in the code6 Use of nested loops7 Use of enums in a non-idiomatic way8 Lack of unit tests9 Violation of single responsibility principle (eg static initializer and multiple methods in the same class) | t | f | f | . Long method2. Complicated code structure3. Lack of comments or documentation4. Poor variable naming (e.g. "builder", "pos", etc.)5. Magic numbers or string literals used in the code6. Use of nested loops7. Use of enums in a non-idiomatic way8. Lack of unit tests9. Violation of single responsibility principle (e.g. static initializer and multiple methods in the same class) | blob | 0 | 12026 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 | 2 | 1804 | 12026 | major |
| 770 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void fillMenuBeforeShow(final IMenuManager manager) { manager.add(openAction); manager.add(downloadToAction); manager.add(addAttachmentAction); manager.add(deleteAttachmentAction); manager.add(new Separator()); final DownloadAttachmentOpenType preferredOpenType = DownloadAttachmentOpenType.getPreferredOpenType(); if (DownloadAttachmentOpenType.BROWSER == preferredOpenType) { manager.add(openLocallyAction); } else { manager.add(openInBrowserAction); } manager.add(copyUrlToClipboardAction); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/wit/FileAttachmentsControl.java/#L469-L486 | 1 | 770 | 7268 | major |
| 1853 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WantPropertyElement extends Frame implements WantsObjectFrameI, HasSubjectFrameI { int liCounter = 1; ANode predicate; ANode object; ANode reify; boolean objectIsBlank = false; public WantPropertyElement(HasSubjectFrameI s, AbsXMLContext x) { super(s, x); } // These three are used as bitfields static final private int TYPEDLITERAL = 1; static final private int EMPTYWITHOBJ = 2; static final private int PARSETYPE = 4; @Override public FrameI startElement(String uri, String localName, String rawName, Attributes atts) throws SAXParseException { clearObject(); if (nonWhiteMsgGiven) taint.isTainted(); nonWhiteMsgGiven = false; if (uri==null || uri.equals("")) { warning(WARN_UNQUALIFIED_ELEMENT,"Unqualified property elements are not allowed. Treated as a relative URI."); } ElementLexer el = new ElementLexer(taint, this, uri, localName, rawName, E_LI, CoreAndOldTerms | E_DESCRIPTION, false); // if (el.badMatch) // warning(ERR_SYNTAX_ERROR,"bad use of " + rawName); predicate = el.goodMatch ? (AResourceInternal) rdf_n(liCounter++) : URIReference.fromQName(this, uri, localName); if (taint.isTainted()) predicate.taint(); taint = new TaintImpl(); AttributeLexer ap = new AttributeLexer(this, // xml: A_XMLLANG | A_XMLBASE | A_XML_OTHER // legal rdf: | A_DATATYPE | A_ID | A_NODEID | A_PARSETYPE | A_RESOURCE | A_TYPE, // bad rdf: A_BADATTRS); int cnt = ap.processSpecials(taint, atts); // These three states are intended as mutually // incompatible, but all three can occur // together. Any two of the three, or all // three is a syntax errror. // Having none of these is legal. final int nextStateCode = (ap.datatype == null ? 0 : TYPEDLITERAL) | (ap.parseType == null ? 0 : PARSETYPE) | (mustBeEmpty(ap, atts, cnt) ? EMPTYWITHOBJ : 0); if (this.badStateCode(nextStateCode)) { warning(errorNumber(nextStateCode), descriptionOfCases(ap, nextStateCode, propertyAttributeDescription(atts, ap, cnt))); } AbsXMLContext x = ap.xml(xml); reify = ap.id == null ? null : URIReference.fromID(this, x, ap.id); if (taint.isTainted()) predicate.taint(); if (mustBeEmpty(ap, atts, cnt)) { if (ap.nodeID != null) { object = new ARPResource(arp, ap.nodeID); checkNodeID_XMLName(object, ap.nodeID); objectIsBlank = true; } if (ap.resource != null) { if (object != null) { if (!badStateCode(nextStateCode)) // otherwise warning already given warning(ERR_SYNTAX_ERROR, "On a property element, only one of the attributes rdf:nodeID or rdf:resource is permitted."); } else object = URIReference.resolve(this, x, ap.resource); } if (object == null) { object = new ARPResource(arp); objectIsBlank = true; } if (taint.isTainted()) object.taint(); processPropertyAttributes(ap, atts, x); } FrameI nextFrame = nextFrame(atts, ap, cnt, nextStateCode, x); if (object != null) { if (taint.isTainted()) object.taint(); theObject(object); } if (taint.isTainted()) predicate.taint(); return nextFrame; } private boolean mustBeEmpty(AttributeLexer ap, Attributes atts, int cnt) { return cnt < atts.getLength() || ap.type != null || ap.nodeID != null || ap.resource != null; } private FrameI nextFrame(Attributes atts, AttributeLexer ap, int cnt, int nextStateCode, AbsXMLContext x) throws SAXParseException { switch (nextStateCode) { case 0: return new WantLiteralValueOrDescription(this, x); case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case PARSETYPE: return withParsetype(ap.parseType, x); case TYPEDLITERAL | EMPTYWITHOBJ: case TYPEDLITERAL: return new WantTypedLiteral(this, ap.datatype, x); case EMPTYWITHOBJ: return new WantEmpty(this, x); } throw new IllegalStateException("impossible"); } private FrameI withParsetype(String pt, AbsXMLContext x) throws SAXParseException { if (pt.equals("Collection")) { return new RDFCollection(this, x); } if (pt.equals("Resource")) { if (object == null) { // in some error cases the object has already been set. object = new ARPResource(arp); objectIsBlank = true; } return new WantPropertyElement(this, x); } if (!pt.equals("Literal")) { warning(WARN_UNKNOWN_PARSETYPE, "Unknown rdf:parseType: '" + pt + "' (treated as 'Literal'."); } return new OuterXMLLiteral(this, x, pt); } @Override String suggestParsetypeLiteral() { return (getParent() instanceof WantTopLevelDescription) ? "" : super .suggestParsetypeLiteral(); } @Override public void aPredAndObj(ANode p, ANode o) { triple(object, p, o); } @Override public void makeSubjectReificationWith(ANode r) { triple(r, RDF_SUBJECT, object); } @Override public void theObject(ANode o) { HasSubjectFrameI p = (HasSubjectFrameI) getParent(); p.aPredAndObj(predicate, o); if (reify != null) { triple(reify, RDF_TYPE, RDF_STATEMENT); triple(reify, RDF_OBJECT, o); triple(reify, RDF_PREDICATE, predicate); p.makeSubjectReificationWith(reify); } } @Override public void endElement() { clearObject(); } @Override public void abort() { clearObject(); } private void clearObject() { if (objectIsBlank) arp.endLocalScope(object); objectIsBlank = false; object = null; } static private URIReference _rdf_n[] = new URIReference[0]; static private URIReference rdf_n(int i) { if (i >= _rdf_n.length) { int newLength = (i + 10) * 3 / 2; URIReference new_rdf_n[] = new URIReference[newLength]; System.arraycopy(_rdf_n, 0, new_rdf_n, 0, _rdf_n.length); for (int j = _rdf_n.length; j < newLength; j++) { new_rdf_n[j] = URIReference.createNoChecks(rdfns + "_" + j); } _rdf_n = new_rdf_n; } return _rdf_n[i]; } /*************************************************************************** * * ERROR HANDLING CODE * **************************************************************************/ // Error detection private boolean badStateCode(int nextStateCode) { switch (nextStateCode) { case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case TYPEDLITERAL | EMPTYWITHOBJ: return true; case 0: case PARSETYPE: case TYPEDLITERAL: case EMPTYWITHOBJ: return false; } throw new IllegalStateException("impossible"); } // Error classification private int errorNumber(int nextStateCode) { // TODO: not for 2.3. refine this error code. return ERR_SYNTAX_ERROR; } /*************************************************************************** * * ERROR MESSAGES * **************************************************************************/ private String descriptionOfCases(AttributeLexer ap, int nextStateCode, String propAttrs) { return ((propAttrs == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && propAttrs == null)) ? pairwiseIncompatibleErrorMessage( nextStateCode, ap, propAttrs) : complicatedErrorMessage(nextStateCode, ap, propAttrs); } private String pairwiseIncompatibleErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { ArrayList cases = new ArrayList<>(); if ((nextStateCode & PARSETYPE) != 0) cases.add("rdf:parseType"); if ((nextStateCode & TYPEDLITERAL) != 0) cases.add("rdf:datatype"); if (ap.nodeID != null) cases.add("rdf:nodeID"); if (ap.resource != null) cases.add("rdf:resource"); if (ap.type != null) cases.add("rdf:type"); if (cases.size() == 1) { if (propAttrs == null) throw new IllegalStateException("Shouldn't happen."); return "The attribute " + cases.get(0) + " is not permitted with " + propAttrs + " on a property element."; } String rslt = "On a property element, only one of the "; if (propAttrs == null) rslt += "attributes "; for (int i = 0; i < cases.size(); i++) { rslt += cases.get(i); switch (cases.size() - i) { case 1: break; case 2: rslt += " or "; break; default: rslt += ", "; break; } } if (propAttrs != null) { rslt += " attributes or " + propAttrs; } rslt += " is permitted."; return rslt; } private String complicatedErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { String subjectIs; if (ap.nodeID == null && ap.resource == null && (ap.type == null || propAttrs == null)) throw new IllegalStateException("precondition failed."); switch (nextStateCode & (TYPEDLITERAL | PARSETYPE)) { case TYPEDLITERAL | PARSETYPE: subjectIs = "the mutually incompatible attributes rdf:datatype and rdf:parseType are"; break; case TYPEDLITERAL: subjectIs = "the attribute rdf:datatype is"; break; case PARSETYPE: subjectIs = "the attribute rdf:parseType is"; break; default: throw new IllegalStateException("precondition failed"); } String nodeIDResource = null; if (ap.nodeID != null && ap.resource != null) { nodeIDResource = "the mutually incompatible attributes rdf:nodeID and rdf:resource"; } else if (ap.nodeID != null) { nodeIDResource = "the attribute rdf:nodeID"; } else if (ap.resource != null) { nodeIDResource = "the attribute rdf:resource"; } int otherAttCount = nodeIDResource == null ? 0 : 1; String otherAtts; if (ap.type != null) otherAttCount++; if (propAttrs != null) otherAttCount++; if (otherAttCount < 2) throw new IllegalStateException("logic error"); otherAtts = otherAttCount == 2 ? "both " : "each of "; if (ap.type != null && propAttrs != null) { if (nodeIDResource == null) otherAtts += "the attribute rdf:type and the " + propAttrs; else otherAtts += "the attribute rdf:type, the " + propAttrs; } else if (ap.type != null) { otherAtts += "the attribute rdf:type"; } else { otherAtts = "the " + propAttrs; } if (nodeIDResource != null) otherAtts += " and "+nodeIDResource; return "On a property element, " + subjectIs + " incompatible with " + otherAtts +"."; } private String propertyAttributeDescription(Attributes atts, AttributeLexer ap, int cnt) { String propAttrs = ""; int propAttrCount = atts.getLength() - cnt; int found = 0; if (propAttrCount == 0) return null; switch (propAttrCount) { case 0: break; case 1: case 2: case 3: for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { propAttrs += atts.getQName(i); found++; switch (propAttrCount - found) { case 0: break; case 1: propAttrs += " and "; break; default: propAttrs += ", "; } } break; default: if (propAttrCount < 0) throw new IllegalStateException("Shouldn't happen."); for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { found++; switch (found) { case 1: propAttrs += atts.getQName(i) + ", "; break; case 2: propAttrs += atts.getQName(i) + ", ..."; break; default: // ignore } } } return "property attributes (" + propAttrs + ")"; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12197 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/states/WantPropertyElement.java/#L27-L436 | 1 | 1853 | 12197 | major |
| 550 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void uncompressed(Blackhole blackhole) { final ImmutableConciseSet set = ImmutableConciseSet.complement(null, emptyRows); blackhole.consume(set); assert (emptyRows == set.size()); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 5563 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/benchmarks/src/main/java/org/apache/druid/benchmark/ConciseComplementBenchmark.java/#L43-L51 | 1 | 550 | 5563 | minor |
| 214 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2325 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 1 | 214 | 2325 | minor |
| 1310 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | f | f | f | feature envy | 0 | 10680 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1310 | 10680 | major | ||
| 3373 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 6419 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 2 | 3373 | 6419 | major | ||
| 2019 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12781 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 2019 | 12781 | major |
| 2332 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | feature envy | t | t | f | feature envy | blob | 0 | 14155 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 1 | 2332 | 14155 | major |
| 2139 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 13262 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 2139 | 13262 | major |
| 375 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LogUtils { private static final String HIVE_L4J = "metastore-log4j2.properties"; private static final Logger l4j = LoggerFactory.getLogger(LogUtils.class); @SuppressWarnings("serial") public static class LogInitializationException extends Exception { LogInitializationException(String msg) { super(msg); } } /** * This is an exception that can be passed to logger just for printing the stacktrace. */ public static class StackTraceLogger extends Exception { public StackTraceLogger(final String msg) { super(msg); } } /** * Initialize log4j. * * @return an message suitable for display to the user * @throws LogInitializationException if log4j fails to initialize correctly */ public static String initHiveLog4j(Configuration conf) throws LogInitializationException { return initHiveLog4jCommon(conf, MetastoreConf.ConfVars.LOG4J_FILE); } private static String initHiveLog4jCommon(Configuration conf, ConfVars confVarName) throws LogInitializationException { if (MetastoreConf.getVar(conf, confVarName).equals("")) { // if log4j configuration file not set, or could not found, use default setting return initHiveLog4jDefault(conf, "", confVarName); } else { // if log4j configuration file found successfully, use HiveConf property value String log4jFileName = MetastoreConf.getVar(conf, confVarName); File log4jConfigFile = new File(log4jFileName); boolean fileExists = log4jConfigFile.exists(); if (!fileExists) { // if property specified file not found in local file system // use default setting return initHiveLog4jDefault( conf, "Not able to find conf file: " + log4jConfigFile, confVarName); } else { // property speficied file found in local file system // use the specified file final boolean async = checkAndSetAsyncLogging(conf); // required for MDC based routing appender so that child threads can inherit the MDC context System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, log4jFileName); logConfigLocation(); return "Logging initialized using configuration in " + log4jConfigFile + " Async: " + async; } } } private static boolean checkAndSetAsyncLogging(final Configuration conf) { final boolean asyncLogging = MetastoreConf.getBoolVar(conf, ConfVars.ASYNC_LOG_ENABLED); if (asyncLogging) { System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); // default is ClassLoaderContextSelector which is created during automatic logging // initialization in a static initialization block. // Changing ContextSelector at runtime requires creating new context factory which will // internally create new context selector based on system property. LogManager.setFactory(new Log4jContextFactory()); } return asyncLogging; } private static String initHiveLog4jDefault(Configuration conf, String logMessage, ConfVars confVarName) throws LogInitializationException { URL hive_l4j = null; switch (confVarName) { case LOG4J_FILE: hive_l4j = LogUtils.class.getClassLoader().getResource(HIVE_L4J); break; default: break; } if (hive_l4j != null) { final boolean async = checkAndSetAsyncLogging(conf); System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, hive_l4j.toString()); logConfigLocation(); return (logMessage + "\n" + "Logging initialized using configuration in " + hive_l4j + " Async: " + async); } else { throw new LogInitializationException( logMessage + "Unable to initialize logging using " + LogUtils.HIVE_L4J + ", not found on CLASSPATH!"); } } private static void logConfigLocation() throws LogInitializationException { // Log a warning if hive-default.xml is found on the classpath if (MetastoreConf.getHiveDefaultLocation() != null) { l4j.warn("DEPRECATED: Ignoring hive-default.xml found on the CLASSPATH at " + MetastoreConf.getHiveDefaultLocation().getPath()); } // Look for hive-site.xml on the CLASSPATH and log its location if found. if (MetastoreConf.getHiveSiteLocation() == null) { l4j.warn("hive-site.xml not found on CLASSPATH"); } else { l4j.debug("Using hive-site.xml found on CLASSPATH at " + MetastoreConf.getHiveSiteLocation().getPath()); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 3872 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/LogUtils.java/#L37-L149 | 1 | 375 | 3872 | minor |
| 467 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Element(endTag=false) public interface LINK extends Attrs, _Child { // $charset omitted /** URI for linked resource * @param uri the URI * @return the current element builder */ LINK $href(String uri); /** language code * @param cdata the code * @return the current element builder */ LINK $hreflang(String cdata); /** advisory content type * @param cdata the type * @return the current element builder */ LINK $type(String cdata); /** forward link types * @param linkTypes the types * @return the current element builder */ LINK $rel(EnumSet linkTypes); /** * forward link types. * @param linkTypes space-separated link types * @return the current element builder */ LINK $rel(String linkTypes); // $rev omitted. Instead of rev="made", use rel="author" /** for rendering on these media * @param mediaTypes the media types * @return the current element builder */ LINK $media(EnumSet mediaTypes); /** * for rendering on these media. * @param mediaTypes comma-separated list of media * @return the current element builder */ LINK $media(String mediaTypes); } |
data class | f | f | f | data class | 0 | 4538 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java/#L1772-L1820 | 1 | 467 | 4538 | major | ||
| 1035 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 1035 | 9397 | minor | ||
| 2173 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13386 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 2173 | 13386 | minor |
| 291 | YES I found bad smells. The bad smells are:1. Long method 2. Method contains test cases instead of just checking properties | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | Long method2 Method contains test cases instead of just checking properties | t | f | f | . Long method2. Method contains test cases instead of just checking properties | blob | 0 | 3076 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 291 | 3076 | critical |
| 5766 | YES I found bad smells 1. Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
feature envy | Long Method | t | f | f | . Long Method | feature envy | 0 | 14655 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5766 | 14655 | major |
| 244 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2649 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 1 | 244 | 2649 | major |
| 1143 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10101 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 1143 | 10101 | minor |
| 1265 | YES I found bad smells 1. Long method 2. Feature envy 3. Code duplication (duplicate code in constructors) 4. Lack of encapsulation (direct access to class variables) 5. Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | Long method2 Feature envy3 Code duplication (duplicate code in constructors)4 Lack of encapsulation (direct access to class variables)5 Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | t | f | f | . Long method2. Feature envy3. Code duplication (duplicate code in constructors)4. Lack of encapsulation (direct access to class variables)5. Violation of Single Responsibility Principle (class has multiple responsibilities - representing a DrillRelNode and a TableScan) | data class | 0 | 10541 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 2 | 1265 | 10541 | minor |
| 853 | YES I found bad smells 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7877 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 853 | 7877 | major |
| 1563 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11316 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 1563 | 11316 | minor |
| 711 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Code duplication within the same method 5. Inconsistent indentation/formatting 6. Ignored exception handling in some places 7. Inconsistent use of curly brackets in if statements 8. Nested function calls with long parameters 9. single line if statements without curly brackets | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Code duplication within the same method5 Inconsistent indentation/formatting6 Ignored exception handling in some places7 Inconsistent use of curly brackets in if statements8 Nested function calls with long parameters9 single line if statements without curly brackets | t | f | f | . Long method2. Feature envy3. Duplicate code4. Code duplication within the same method5. Inconsistent indentation/formatting6. Ignored exception handling in some places7. Inconsistent use of curly brackets in if statements8. Nested function calls with long parameters9. single line if statements without curly brackets | blob | 0 | 6777 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 2 | 711 | 6777 | minor |
| 2421 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14434 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 2421 | 14434 | critical |
| 2704 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15338 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 2704 | 15338 | major |
| 3570 | YES I found bad smells The bad smells are: 1. Duplicate code 2. Long class 3. Data class 4. Large class 5. Data clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
blob | Duplicate code2 Long class3 Data class4 Large class5 Data clumps | t | f | f | . Duplicate code2. Long class3. Data class4. Large class5. Data clumps | blob | 0 | 7852 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 3570 | 7852 | minor |
| 515 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 5310 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 2 | 515 | 5310 | minor |
| 951 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 8525 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 1 | 951 | 8525 | minor |
| 830 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7736 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 2 | 830 | 7736 | minor |
| 719 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6829 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 719 | 6829 | minor |
| 5248 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class GenericConnectionStatusHtmlCreator { public static String generateConnectionViewHtml(String providerDisplayName, String providerId, UserProfile profile) { String escProviderDisplayName = escape(providerDisplayName); StringBuilder builder = new StringBuilder(); if (profile == null) { builder.append("Connect to " + escProviderDisplayName + ""); builder.append(""); builder.append(""); builder.append("You aren't connected to "); builder.append(escProviderDisplayName); builder.append(" yet. Click the button to connect with your "); builder.append(escProviderDisplayName); builder.append(" account."); builder.append(""); builder.append("Connect to "); builder.append(escProviderDisplayName); builder.append(""); builder.append(""); } else { String escProfileName = escape(profile.getName()); builder.append("Connected to "); builder.append(escProviderDisplayName); builder.append(""); builder.append("Hello, "); builder.append(escProfileName); builder.append("!You are now connected to "); builder.append(escProviderDisplayName); String username = profile.getUsername(); if (username !=null) { builder.append(" as "); builder.append(escape(username)); } builder.append("."); } return builder.toString(); } private static String escape(String in) { return htmlEscape(in).replaceAll("\\{", "{").replaceAll("\\}", "}"); } } } |
blob | long method | t | t | f | long method | blob | 0 | 14677 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-web/src/main/java/org/springframework/social/connect/web/GenericConnectionStatusView.java/#L91-L138 | 1 | 5248 | 14677 | minor |
| 23 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 688 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 2 | 23 | 688 | minor |
| 1464 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } } |
blob | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers. | blob | 0 | 11029 | https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 | 2 | 1464 | 11029 | minor |
| 1858 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12217 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 1858 | 12217 | major |
| 2629 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15089 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 1 | 2629 | 15089 | minor |
| 66 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Solaris extends OperatingSystem.Unix { @Override public String getFamilyName() { return "solaris"; } @Override protected String getOsPrefix() { return "sunos"; } @Override protected String getArch() { String arch = System.getProperty("os.arch"); if (arch.equals("i386") || arch.equals("x86")) { return "x86"; } return super.getArch(); } } |
data class | long method | t | t | f | long method | data class | 0 | 1074 | https://github.com/linkedin/pygradle/blob/4b04b7980dc47a76b816184ebbcfe0b3f5cefadd/pygradle-plugin/src/main/groovy/com/linkedin/gradle/python/util/OperatingSystem.java/#L363-L382 | 1 | 66 | 1074 | major |
| 135 | { "response": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1664 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 135 | 1664 | major |
| 989 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9013 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 1 | 989 | 9013 | major |
| 2252 | YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long Method, 2 Feature Envy | t | f | f | . Long Method, 2. Feature Envy. | data class | 0 | 13680 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 2252 | 13680 | major |
| 2249 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class 3. Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions 4. Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable 5. Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation 6. Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities. 7. Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere. 8. Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues. 9. Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method2 Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class3 Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions4 Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable5 Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation6 Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities7 Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere8 Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues9 Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary | t | f | f | . Long method2. Feature envy: LimitedSizeDataCollection class is accessing and manipulating the data HashMap belonging to another class3. Inconsistent naming conventions: The class name and method names are not consistent with the rest of the code's naming conventions4. Magic numbers: The limitedSize value is hard-coded to a specific number instead of being declared as a constant or configurable variable5. Incomplete exception handling: The UnsupportedOperationException is thrown for certain methods without any further handling or explanation6. Multiple responsibilities: The LimitedSizeDataCollection class is responsible for both storing data in its own HashMap as well as providing methods for reading and writing data, causing it to have multiple responsibilities.7. Misplaced methods: The writing and reading methods and variables do not seem to be relevant to the purpose of the LimitedSizeDataCollection class and should be located elsewhere.8. Potential for data inconsistency: Since the writing and reading variables are volatile and can be accessed and modified by multiple methods, there is a potential for data inconsistency and synchronization issues.9. Unnecessary comments: Some comments are providing redundant or obvious information and are not necessary. | data class | 0 | 13663 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 2249 | 13663 | minor |
| 1918 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming/abbreviations 4. Code duplication 5. Nested conditional statements 6. Magic numbers 7. Use of nested functions instead of separate methods 8. Lack of proper error handling and exception handling 9. Complex logic and too many dependencies. 10. Lack of comments and documentation 11. Repetitive coding patterns 12. Poor use of logging statements 13. Mixing of business logic and technical logic in the same method 14. Inadequate separation of concerns 15. Inflexible and tightly coupled code 16. Use of deprecated methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | Long method2 Feature envy3 Inconsistent naming/abbreviations4 Code duplication5 Nested conditional statements6 Magic numbers7 Use of nested functions instead of separate methods8 Lack of proper error handling and exception handling9 Complex logic and too many dependencies | t | f | f | . Long method2. Feature envy3. Inconsistent naming/abbreviations4. Code duplication5. Nested conditional statements6. Magic numbers7. Use of nested functions instead of separate methods8. Lack of proper error handling and exception handling9. Complex logic and too many dependencies. | blob | 0 | 12411 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 2 | 1918 | 12411 | major |
| 440 | {"message": "YES I found bad smells", "bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: interface Failover { String PREFIX = HdfsClientConfigKeys.PREFIX + "failover."; String PROXY_PROVIDER_KEY_PREFIX = PREFIX + "proxy.provider"; String MAX_ATTEMPTS_KEY = PREFIX + "max.attempts"; int MAX_ATTEMPTS_DEFAULT = 15; String SLEEPTIME_BASE_KEY = PREFIX + "sleep.base.millis"; int SLEEPTIME_BASE_DEFAULT = 500; String SLEEPTIME_MAX_KEY = PREFIX + "sleep.max.millis"; int SLEEPTIME_MAX_DEFAULT = 15000; String CONNECTION_RETRIES_KEY = PREFIX + "connection.retries"; int CONNECTION_RETRIES_DEFAULT = 0; String CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = PREFIX + "connection.retries.on.timeouts"; int CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; String RANDOM_ORDER = PREFIX + "random.order"; boolean RANDOM_ORDER_DEFAULT = false; String RESOLVE_ADDRESS_NEEDED_KEY = PREFIX + "resolve-needed"; boolean RESOLVE_ADDRESS_NEEDED_DEFAULT = false; String RESOLVE_SERVICE_KEY = PREFIX + "resolver.impl"; } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4300 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java/#L274-L294 | 1 | 440 | 4300 | major |
| 538 | YES I found bad smells the bad smells are: 1. Long constructor 2. Redundant ternary operation 3. Poor naming conventions for variables 4. Lack of encapsulation for instance variables 5. Unnecessary use of intern() method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | Long constructor2 Redundant ternary operation3 Poor naming conventions for variables4 Lack of encapsulation for instance variables5 Unnecessary use of intern() method | t | f | f | . Long constructor2. Redundant ternary operation3. Poor naming conventions for variables4. Lack of encapsulation for instance variables5. Unnecessary use of intern() method | data class | 0 | 5500 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 2 | 538 | 5500 | major |
| 3925 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 10274 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 3925 | 10274 | critical |
| 1966 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
blob | data class | t | t | f | data class | blob | 0 | 12599 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 1 | 1966 | 12599 | critical |
| 504 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 5124 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 1 | 504 | 5124 | minor |
| 2695 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 15315 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 1 | 2695 | 15315 | minor |
| 33 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 732 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 33 | 732 | major |
| 1120 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9974 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 2 | 1120 | 9974 | minor |
| 4881 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13281 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 2 | 4881 | 13281 | minor | ||
| 1670 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code/redundancy 4. Inconsistent formatting/scattered code 5. Incomplete encapsulation/leaky abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
blob | Long method2 Feature envy3 Duplicate code/redundancy4 Inconsistent formatting/scattered code5 Incomplete encapsulation/leaky abstraction | t | f | f | . Long method2. Feature envy3. Duplicate code/redundancy4. Inconsistent formatting/scattered code5. Incomplete encapsulation/leaky abstraction | blob | 0 | 11632 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 2 | 1670 | 11632 | minor |
| 1811 | YES I found bad smells The bad smells are: 1. Deprecated class without further explanation 2. Two getter and setter methods 3. No clear purpose or functionality of the class 4. Naming inconsistency (offset vs producerGroup) 5. Lack of encapsulation as variables are directly accessible without methods for validation or control. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Deprecated class without further explanation2 Two getter and setter methods 3 No clear purpose or functionality of the class4 Naming inconsistency (offset vs producerGroup) 5 Lack of encapsulation as variables are directly accessible without methods for validation or control | t | f | f | . Deprecated class without further explanation2. Two getter and setter methods 3. No clear purpose or functionality of the class4. Naming inconsistency (offset vs producerGroup) 5. Lack of encapsulation as variables are directly accessible without methods for validation or control. | data class | 0 | 12061 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 1811 | 12061 | minor |
| 551 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5564 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 551 | 5564 | major |
| 1643 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11556 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 | 2 | 1643 | 11556 | critical |
| 638 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Redundant code/wasted code 4. Magic numbers 5. Long parameter list 6. Insufficient JavaDocs NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } } |
blob | Long method 2 Feature envy3 Redundant code/wasted code 4 Magic numbers 5 Long parameter list6 Insufficient JavaDocs NO, I did not find any bad smell | t | f | f | . Long method 2. Feature envy3. Redundant code/wasted code 4. Magic numbers 5. Long parameter list6. Insufficient JavaDocs NO, I did not find any bad smell. | blob | 0 | 6319 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 | 2 | 638 | 6319 | major |
| 1537 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | t | f | f | long method | 0 | 11223 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 1537 | 11223 | major | ||
| 172 | {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2039 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 1 | 172 | 2039 | critical |
| 2656 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 15183 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 2656 | 15183 | minor |
| 1456 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
blob | data class | t | t | f | data class | blob | 0 | 11010 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 1 | 1456 | 11010 | critical |
| 2321 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14130 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 2321 | 14130 | major |
| 389 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XPathParser { private final Map prefixes = new HashMap(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // for compatibility return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } } |
blob | long method | t | t | f | long method | blob | 0 | 3948 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/sax/xpath/XPathParser.java/#L40-L120 | 1 | 389 | 3948 | minor |
| 2085 | Yes I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Duplicated code, 4. Inappropriate naming, 5. Primitive Obsession, 6. Lazy Class, 7. Zero functionality, 8. Unnecessary comments, 9. Unused variables, 10. Empty catch block | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | Long method, 2 Feature envy, 3 Duplicated code, 4 Inappropriate naming, 5 Primitive Obsession, 6 Lazy Class, 7 Zero functionality, 8 Unnecessary comments, 9 Unused variables, | t | f | f | . Long method, 2. Feature envy, 3. Duplicated code, 4. Inappropriate naming, 5. Primitive Obsession, 6. Lazy Class, 7. Zero functionality, 8. Unnecessary comments, 9. Unused variables, | blob | 0 | 13099 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 2085 | 13099 | minor |
| 833 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7743 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 2 | 833 | 7743 | minor |
| 2280 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Poor variable naming 5. Mix of string concatenation and string formatting methods 6. Code formatting issues 7. Lack of comments or documentation 8. Lack of access modifiers for class fields 9. Lack of proper exception handling 10. Unnecessary override of methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Long method2 Feature envy3 Code duplication4 Poor variable naming5 Mix of string concatenation and string formatting methods 6 Code formatting issues 7 Lack of comments or documentation8 Lack of access modifiers for class fields9 Lack of proper exception handling | t | f | f | . Long method2. Feature envy3. Code duplication4. Poor variable naming5. Mix of string concatenation and string formatting methods 6. Code formatting issues 7. Lack of comments or documentation8. Lack of access modifiers for class fields9. Lack of proper exception handling | data class | 0 | 13797 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 2280 | 13797 | minor |
| 1170 | { "message": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | data class | 0 | 10194 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 1 | 1170 | 10194 | minor |
| 4823 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 13121 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 2 | 4823 | 13121 | minor | ||
| 844 | "YES I found bad smells",1.Long method,2.Feature envy,3.Magic number,4.Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable public final class ConnectionValidator { private final Map specMap; private final QueryFilterCriteriaFactory queryFilterCriteriaFactory; private ConnectionValidator(final AbstractProtocolValidator... connectionSpecs) { final Map specMap = Arrays.stream(connectionSpecs) .collect(Collectors.toMap(AbstractProtocolValidator::type, Function.identity())); this.specMap = Collections.unmodifiableMap(specMap); final CriteriaFactory criteriaFactory = new CriteriaFactoryImpl(); final ThingsFieldExpressionFactory fieldExpressionFactory = new ModelBasedThingsFieldExpressionFactory(); queryFilterCriteriaFactory = new QueryFilterCriteriaFactory(criteriaFactory, fieldExpressionFactory); } /** * Create a connection validator from connection specs. * * @param connectionSpecs specs of supported connection types. * @return a connection validator. */ public static ConnectionValidator of(final AbstractProtocolValidator... connectionSpecs) { return new ConnectionValidator(connectionSpecs); } /** * Check a connection for errors and throw them. * * @param connection the connection to validate. * @param dittoHeaders headers of the command that triggered the connection validation. * @throws org.eclipse.ditto.model.base.exceptions.DittoRuntimeException if the connection has errors. * @throws java.lang.IllegalStateException if the connection type is not known. */ void validate(final Connection connection, final DittoHeaders dittoHeaders) { final AbstractProtocolValidator spec = specMap.get(connection.getConnectionType()); validateSourceAndTargetAddressesAreNonempty(connection, dittoHeaders); validateFormatOfCertificates(connection, dittoHeaders); if (spec != null) { // throw error at validation site for clarity of stack trace spec.validate(connection, dittoHeaders); } else { throw new IllegalStateException("Unknown connection type: " + connection); } } private void validateSourceAndTargetAddressesAreNonempty(final Connection connection, final DittoHeaders dittoHeaders) { connection.getSources().forEach(source -> { if (source.getAddresses().isEmpty() || source.getAddresses().contains("")) { final String location = String.format("Source %d of connection <%s>", source.getIndex(), connection.getId()); throw emptyAddressesError(location, dittoHeaders); } }); connection.getTargets().forEach(target -> { if (target.getAddress().isEmpty()) { final String location = String.format("Targets of connection <%s>", connection.getId()); throw emptyAddressesError(location, dittoHeaders); } target.getTopics().forEach(topic -> topic.getFilter().ifPresent(filter -> { // will throw an InvalidRqlExpressionException if the RQL expression was not valid: queryFilterCriteriaFactory.filterCriteria(filter, dittoHeaders); })); }); } private static void validateFormatOfCertificates(final Connection connection, final DittoHeaders dittoHeaders) { final Optional trustedCertificates = connection.getTrustedCertificates(); final Optional credentials = connection.getCredentials(); // check if there are certificates to check if (trustedCertificates.isPresent() || credentials.isPresent()) { credentials.orElseGet(ClientCertificateCredentials::empty) .accept(SSLContextCreator.fromConnection(connection, dittoHeaders)); } } private static DittoRuntimeException emptyAddressesError(final String location, final DittoHeaders dittoHeaders) { final String message = location + ": addresses may not be empty."; return ConnectionConfigurationInvalidException.newBuilder(message) .dittoHeaders(dittoHeaders) .build(); } } |
blob | Long method,2Feature envy,3Magic number,4Long parameter list | t | f | f | .Long method, 2.Feature envy, 3.Magic number, 4.Long parameter list | blob | 0 | 7807 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/connectivity/messaging/src/main/java/org/eclipse/ditto/services/connectivity/messaging/validation/ConnectionValidator.java/#L39-L125 | 2 | 844 | 7807 | minor |
| 176 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface DedicatedService extends PluggableService { DedicatePodResponse createDedicatePodResponse(DedicatedResources resource); DedicateClusterResponse createDedicateClusterResponse(DedicatedResources resource); DedicateHostResponse createDedicateHostResponse(DedicatedResources resource); Pair, Integer> listDedicatedPods(ListDedicatedPodsCmd cmd); Pair, Integer> listDedicatedHosts(ListDedicatedHostsCmd cmd); Pair, Integer> listDedicatedClusters(ListDedicatedClustersCmd cmd); boolean releaseDedicatedResource(Long zoneId, Long podId, Long clusterId, Long hostId); DedicateZoneResponse createDedicateZoneResponse(DedicatedResources resource); Pair, Integer> listDedicatedZones(ListDedicatedZonesCmd cmd); List dedicateZone(Long zoneId, Long domainId, String accountName); List dedicatePod(Long podId, Long domainId, String accountName); List dedicateCluster(Long clusterId, Long domainId, String accountName); List dedicateHost(Long hostId, Long domainId, String accountName); } |
blob | long method | t | t | f | long method | blob | 0 | 2050 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/dedicated-resources/src/main/java/org/apache/cloudstack/dedicated/DedicatedService.java/#L35-L63 | 1 | 176 | 2050 | minor |
| 2682 | {"message": "YES, I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15268 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 2682 | 15268 | major |
| 567 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } } |
blob | data class | t | t | f | data class | blob | 0 | 5724 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 | 1 | 567 | 5724 | minor |
| 251 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public final class ShortSerializer extends TypeSerializerSingleton { private static final long serialVersionUID = 1L; /** Sharable instance of the ShortSerializer. */ public static final ShortSerializer INSTANCE = new ShortSerializer(); private static final Short ZERO = (short) 0; @Override public boolean isImmutableType() { return true; } @Override public Short createInstance() { return ZERO; } @Override public Short copy(Short from) { return from; } @Override public Short copy(Short from, Short reuse) { return from; } @Override public int getLength() { return 2; } @Override public void serialize(Short record, DataOutputView target) throws IOException { target.writeShort(record); } @Override public Short deserialize(DataInputView source) throws IOException { return source.readShort(); } @Override public Short deserialize(Short reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { target.writeShort(source.readShort()); } @Override public TypeSerializerSnapshot snapshotConfiguration() { return new ShortSerializerSnapshot(); } // ------------------------------------------------------------------------ /** * Serializer configuration snapshot for compatibility and format evolution. */ @SuppressWarnings("WeakerAccess") public static final class ShortSerializerSnapshot extends SimpleTypeSerializerSnapshot { public ShortSerializerSnapshot() { super(() -> INSTANCE); } } } |
data class | Not specified | f | f | f | false | 0 | 2690 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortSerializer.java/#L32-L104 | 2 | 251 | 2690 | minor | |
| 2196 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13481 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 2 | 2196 | 13481 | minor |
| 305 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3185 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 305 | 3185 | minor |
| 252 | {"response": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
blob | Not specified | f | f | f | false | 0 | 2712 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 2 | 252 | 2712 | minor | |
| 1955 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12554 | https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 | 2 | 1955 | 12554 | critical |
| 3820 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GlobbingPathHelper { /** * Converts the provided path containing glob characters * * and ** into a regular expression. The definition matches * that of the GlobbingPathFilter with the addition that this conversion * also supports sub-paths which do not start with a /. * * The rules are: * * leading ** matches /foo and bar * leading /** matches /foo but not bar * intermittent ** matches zero or any number of path elements * trailing ** matches anything not ending with a / * single * matches anything except / * ? is not a special character * anything not a star is wrapped into \Q...\E pairs * * @param pathWithGlobs path that can contain * and ** * @return a regular expression * @see GlobbingPathFilter */ public static String globPathAsRegex(String pathWithGlobs) { if (pathWithGlobs == null) { return null; } else if (!pathWithGlobs.contains("*")) { return pathWithGlobs; } List elements = Lists.newLinkedList(elements(pathWithGlobs)); StringBuffer sb = new StringBuffer(); sb.append("\\Q"); if (pathWithGlobs.startsWith("/")) { sb.append("/"); } if (elements.get(0).equals("**")) { sb.append("\\E[^/]*(/[^/]*)*\\Q"); elements.remove(0); } int size = elements.size(); boolean endsWithStarStar = size == 0 ? false : elements.get(size - 1).equals("**"); if (endsWithStarStar) { elements.remove(size - 1); } boolean addSlash = false; for(int i=0; i<elements.size(); i++) { String pathElem = elements.get(i); if (addSlash) { sb.append("/"); } if (pathElem.equals("**")) { addSlash = false; sb.append("\\E([^/]*/)*\\Q"); } else { sb.append(pathElem.replace("*", "\\E[^/]*\\Q")); addSlash = true; } } if (endsWithStarStar) { sb.append("\\E(/[^/]*)*"); } else if (pathWithGlobs.endsWith("/")) { sb.append("/\\E"); } else { sb.append("\\E"); } return sb.toString(); } } |
blob | long method | t | t | f | long method | blob | 0 | 9761 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/observation/filter/GlobbingPathHelper.java/#L27-L94 | 1 | 3820 | 9761 | minor |
| 1471 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11050 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 1 | 1471 | 11050 | critical |
| 2054 | YES I found bad smells, the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 12922 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 2054 | 12922 | minor |
| 586 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 5819 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/protocol/src/main/java/org/apache/drill/exec/proto/UserProtos.java/#L19445-L20118 | 2 | 586 | 5819 | major | ||
| 4167 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10969 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 4167 | 10969 | minor |
| 533 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
data class | long method | t | t | f | long method | data class | 0 | 5479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 1 | 533 | 5479 | minor |
| 1065 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Not specified | f | f | f | false | 0 | 9567 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 1 | 1065 | 9567 | minor | |
| 2358 | { "output": "YES I found bad smells, the bad smells are: 1. Long method", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14233 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 2358 | 14233 | major |
| 1854 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12206 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 2 | 1854 | 12206 | minor |
| 156 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ArgumentProcessor getProcessor( Class< ? extends ArgumentProcessor> processorClass) { ArgumentProcessor processor; try { processor = processorClass.getConstructor().newInstance(); } catch (Exception e) { throw new BuildException("The argument processor class" + processorClass.getName() + " could not be instantiated with a default constructor", e); } return processor; } |
feature envy | f | f | f | feature envy | 0 | 1968 | https://github.com/apache/ant/blob/9722f062dc68d6c321faf751621162ac8444c585/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java/#L121-L133 | 2 | 156 | 1968 | minor | |||
| 4153 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10936 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 1 | 4153 | 10936 | critical |
| 2522 | {"message": "YES I found bad smells", "bad smells are:": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
blob | long method | t | t | f | long method | blob | 0 | 14711 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 2522 | 14711 | minor |
| 1427 | * @param aggregatedModules set of already aggregated modules */ YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10945 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 2 | 1427 | 10945 | minor |
| 1731 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 11820 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 1 | 1731 | 11820 | major |
| 4637 | "I did not find any bad smell." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12373 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L54340-L54409 | 2 | 4637 | 12373 | minor | ||
| 1290 | { "output": "YES, I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10616 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 1290 | 10616 | minor |
| 719 | {"answer": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6829 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 719 | 6829 | minor |
| 1667 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; private final AbstractPathConfiguration classpathConfiguration; private final ClassLoaderConfiguration classLoaderConfiguration; private final boolean isForkRequested; private final boolean isInForkedVm; public StartupConfiguration( @Nonnull String providerClassName, @Nonnull AbstractPathConfiguration classpathConfiguration, @Nonnull ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } public boolean isProviderMainClass() { return providerClassName.endsWith( "#main" ); } public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) { return new StartupConfiguration( providerClassName, classpathConfiguration, classLoaderConfiguration, true, true ); } public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } @Deprecated public boolean useSystemClassLoader() { // todo; I am not totally convinced this logic is as simple as it could be return classLoaderConfiguration.isUseSystemClassLoader() && ( isInForkedVm || isForkRequested ); } public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } public String getProviderClassName() { return providerClassName; } public String getActualClassName() { return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; } /** * Strip any of a supplied String from the end of a String. * * If the strip String is {@code null}, whitespace is * stripped. * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ private static String stripEnd( String str, String strip ) { if ( str == null ) { return null; } int end = str.length(); if ( strip == null ) { while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) { end--; } } else { while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) { end--; } } return str.substring( 0, end ); } public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } public boolean isShadefire() { return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); } public void writeSurefireTestClasspathProperty() { getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11625 | https://github.com/apache/maven-surefire/blob/e57f76c7e858dbbaac6be4cbcd16e215de10b064/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java/#L29-L140 | 1 | 1667 | 11625 | minor |
| 3875 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10123 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 2 | 3875 | 10123 | major |
| 1297 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10637 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 2 | 1297 | 10637 | major |
| 2389 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14353 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/THBaseService.java/#L12256-L12314 | 2 | 2389 | 14353 | major | ||
| 239 | {"NO, I did not find any bad smell" : 1.1} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
blob | f | f | f | blob | 0 | 2614 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 239 | 2614 | minor | ||
| 2151 | YES I found bad smells the bad smells are: 1. Long method 2. Shotgun surgical 3. Lazy class 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | Long method2 Shotgun surgical3 Lazy class4 Feature envy | t | f | f | . Long method2. Shotgun surgical3. Lazy class4. Feature envy | blob | 0 | 13293 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 2151 | 13293 | minor |
| 2295 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13990 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 1 | 2295 | 13990 | minor |
| 4680 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuckAddDependencyIntention extends BaseIntentionAction { private static Logger LOGGER = Logger.getInstance(BuckAddDependencyIntention.class); /** * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the * given reference element to those of the given psiClass. * * Note that this intention can fail to be created if either side of the edge cannot be * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking * this intention may fail to create edges in either the Buck target graph or the IntelliJ module * graph (or both). */ @Nullable public static BuckAddDependencyIntention create( PsiJavaCodeReferenceElement referenceElement, PsiClass psiClass) { VirtualFile editSourceFile = referenceElement.getContainingFile().getVirtualFile(); if (editSourceFile == null) { return null; } Project project = referenceElement.getProject(); BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); VirtualFile editBuildFile = buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null); if (editBuildFile == null) { return null; } VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile(); if (importSourceFile == null) { return null; } VirtualFile importBuildFile = buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null); if (importBuildFile == null) { return null; } if (importBuildFile.equals(editBuildFile)) { return null; } ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); Module editModule = projectFileIndex.getModuleForFile(editSourceFile); if (editModule == null) { return null; } Module importModule = projectFileIndex.getModuleForFile(importSourceFile); if (importModule == null) { return null; } BuckTarget editSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(editSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (editSourceTarget == null) { return null; } BuckTarget importSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(importSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (importSourceTarget == null) { return null; } return new BuckAddDependencyIntention( project, referenceElement, editBuildFile, editSourceFile, editSourceTarget, editModule, psiClass, importBuildFile, importSourceFile, importSourceTarget, importModule); } private Project project; // Fields pertaining to the element in the file being edited private PsiJavaCodeReferenceElement referenceElement; private VirtualFile editBuildFile; private VirtualFile editSourceFile; private BuckTarget editSourceTarget; private BuckTarget editTarget; private Module editModule; // Fields pertaining to the dependency that should be resolved/imported private PsiClass psiClass; private VirtualFile importBuildFile; private VirtualFile importSourceFile; private BuckTarget importSourceTarget; private BuckTarget importTarget; private Module importModule; BuckAddDependencyIntention( Project project, PsiJavaCodeReferenceElement referenceElement, VirtualFile editBuildFile, VirtualFile editSourceFile, BuckTarget editSourceTarget, Module editModule, PsiClass psiClass, VirtualFile importBuildFile, VirtualFile importSourceFile, BuckTarget importSourceTarget, Module importModule) { this.project = project; this.referenceElement = referenceElement; this.editBuildFile = editBuildFile; this.editSourceFile = editSourceFile; this.editSourceTarget = editSourceTarget; this.editModule = editModule; this.psiClass = psiClass; this.importBuildFile = importBuildFile; this.importSourceFile = importSourceFile; this.importSourceTarget = importSourceTarget; this.importModule = importModule; String message = "Add BUCK dependency on owner(" + importSourceTarget + ")"; setText(message); } @Nls(capitalization = Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return this.getClass().getSimpleName(); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { String msg = "Invoked for project " + project.getName() + " and file " + psiFile.getName(); LOGGER.info(msg); queryBuckForTargets(editor); } /** Helper class to handle deserialization of buck query. */ static class TargetMetadata { public BuckTarget target; public @Nullable List deps; public @Nullable List visibility; // null means PUBLIC public @Nullable List srcs; public @Nullable List resources; static TargetMetadata from( BuckTargetLocator buckTargetLocator, BuckTarget target, JsonObject payload) { TargetMetadata targetMetadata = new TargetMetadata(); targetMetadata.target = target; targetMetadata.srcs = stringListOrNull(payload.get("srcs")); targetMetadata.resources = stringListOrNull(payload.get("resources")); // Deps are a list of BuckTargets targetMetadata.deps = Optional.ofNullable(stringListOrNull(payload.get("deps"))) .map( deps -> deps.stream() .map( s -> BuckTarget.parse(s).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList())) .orElse(null); // Visibilility falls in one of three cases: // (1) if unspecified => means visibility is limited to the current package // (2) contains "PUBLIC" => available everywhere // (3) otherwise is a list of buck target patterns where it is visible List optionalVisibility = stringListOrNull(payload.get("visibility")); if (optionalVisibility == null) { targetMetadata.visibility = Collections.singletonList(target.asPattern().asPackageMatchingPattern()); } else if (optionalVisibility.contains("PUBLIC")) { targetMetadata.visibility = null; // } else { targetMetadata.visibility = optionalVisibility .stream() .map(p -> BuckTargetPattern.parse(p).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList()); } return targetMetadata; } static @Nullable List stringListOrNull(@Nullable JsonElement jsonElement) { if (jsonElement == null) { return null; } return new Gson().fromJson(jsonElement, new TypeToken>() {}.getType()); } boolean isVisibleTo(BuckTarget target) { if (visibility == null) { return true; } return visibility.stream().anyMatch(pattern -> pattern.matches(target)); } boolean hasDependencyOn(BuckTarget target) { return deps.stream().anyMatch(dep -> dep.equals(target)); } boolean contains(BuckTarget targetFile) { if (!target.asPattern().asPackageMatchingPattern().matches(targetFile)) { return false; } String relativeToBuildFile = targetFile.getRuleName(); return srcs.contains(relativeToBuildFile) || resources.contains(relativeToBuildFile); } } /** Queries buck for targets that own the editSourceFile and the importSourceFile. */ private void queryBuckForTargets(Editor editor) { BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); String editPath = editSourceFile.getPath(); String importPath = importSourceFile.getPath(); BuckJsonCommandHandler> handler = new BuckJsonCommandHandler<>( project, BuckCommand.QUERY, new Callback>() { @Override public List deserialize(JsonElement jsonElement) throws IOException { Type type = new TypeToken>() {}.getType(); Map raw = new Gson().fromJson(jsonElement, type); List results = new ArrayList<>(); for (Entry entry : raw.entrySet()) { BuckTarget.parse(entry.getKey()) .map(buckTargetLocator::resolve) .map( target -> TargetMetadata.from(buckTargetLocator, target, entry.getValue())) .ifPresent(results::add); } return results; } @Override public void onSuccess(List results, String stderr) { List editTargets = new ArrayList<>(); List importTargets = new ArrayList<>(); for (TargetMetadata targetMetadata : results) { if (targetMetadata.contains(editSourceTarget)) { editTargets.add(targetMetadata); } if (targetMetadata.contains(importSourceTarget)) { importTargets.add(targetMetadata); } } updateDependencies(editor, editTargets, importTargets); } @Override public void onFailure( String stdout, String stderr, @Nullable Integer exitCode, @Nullable Throwable throwable) { BuckNotification.getInstance(project) .showWarningBalloon( "Could not determine owners for " + editSourceFile + " and/or " + importSourceFile); return; } }); handler .command() .addParameters( "owner(%s)", editPath, importPath, "--output-attributes=deps|srcs|visibility|resources"); handler.runInCurrentThreadPostEnd(() -> {}); } /** * Implementation of {@link * com.intellij.notification.NotificationListener#hyperlinkUpdate(Notification, HyperlinkEvent)}. */ private void hyperlinkActivated( @NotNull Notification notification, @NotNull HyperlinkEvent event) { String href = event.getDescription(); switch (href) { case "editTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(editTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "editBuildFile": FileEditorManager.getInstance(project).openFile(editBuildFile, true); break; case "editSourceFile": FileEditorManager.getInstance(project).openFile(editSourceFile, true); break; case "importTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(importTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "importBuildFile": FileEditorManager.getInstance(project).openFile(importBuildFile, true); break; case "importSourceFile": FileEditorManager.getInstance(project).openFile(importSourceFile, true); break; } } private void updateDependencies( Editor editor, List editTargets, List importTargets) { if (editTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + editSourceTarget + " in " + editBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (importTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + importSourceTarget + " in " + importBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } TargetMetadata editTargetMetadata = editTargets.get(0); TargetMetadata importTargetMetadata = importTargets.get(0); editTarget = editTargetMetadata.target; importTarget = importTargetMetadata.target; if (!importTargetMetadata.isVisibleTo(editTarget)) { String message = "Add dependency failed: The target " + importTarget + " is not visible to " + editTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (!editTargetMetadata.hasDependencyOn(importTarget)) { if (!BuckDeps.modifyTargetToAddDependency( editBuildFile, editTarget.toString(), importTarget.toString())) { String message = "Add dependency failed: Could not add modify build file for " + editTarget + " to add dependency on " + importTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } } else { String message = "No need to modify build file " + editBuildFile + ", already has dependency from " + editTarget + " to " + importTarget + ""; BuckNotification.getInstance(project).showInfoBalloon(message, this::hyperlinkActivated); } ModuleRootModificationUtil.updateModel( editModule, (modifiableRootModel -> { if (modifiableRootModel.findModuleOrderEntry(importModule) != null) { LOGGER.info( "No need to modify module " + editModule.getName() + ", already has dependency on " + importModule.getName()); } else { modifiableRootModel.addModuleOrderEntry(importModule); LOGGER.info( "Successfully added module dependency from " + editModule.getName() + " on " + importModule.getName()); } new AddImportAction(project, referenceElement, editor, psiClass).execute(); })); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12526 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/autodeps/BuckAddDependencyIntention.java/#L66-L480 | 1 | 4680 | 12526 | critical |
| 2603 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | Long method2Feature envy | t | f | f | .Long method2.Feature envy | blob | 0 | 15024 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 2 | 2603 | 15024 | major |
| 634 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean isValid(Document xml) throws SAXException{ try{ String language = "http://www.w3.org/2001/XMLSchema"; SchemaFactory factory = SchemaFactory.newInstance(language); Source source = new DOMSource(map.getSchema()); Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(xml)); //if no exceptions where raised, the document is valid return true; } catch(IOException e) { LOG.log(POILogger.ERROR, "document is not valid", e); } return false; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6296 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java/#L243-L260 | 1 | 634 | 6296 | minor |
| 3966 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 10400 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 1 | 3966 | 10400 | minor | ||
| 2435 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 14466 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 2435 | 14466 | minor |
| 2700 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 15327 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 1 | 2700 | 15327 | minor |
| 1675 | YES I found bad smells the bad smells are: Duplicated code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | Duplicated code | t | f | f | Duplicated code | long method | 0 | 11644 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 1675 | 11644 | minor |
| 776 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy (methods accessing and modifying fields from a different class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Long method 2 Feature envy (methods accessing and modifying fields from a different class) | t | f | f | . Long method 2. Feature envy (methods accessing and modifying fields from a different class) | data class | 0 | 7362 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 776 | 7362 | major |
| 1542 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11240 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 1542 | 11240 | critical |
| 1524 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11182 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 1524 | 11182 | major |
| 4521 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11993 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 | 2 | 4521 | 11993 | critical |
| 1215 | } YES I found bad smells the bad smells are: 1. Debug code - commented out code and print statements that are not needed for production. 2. Inconsistent formatting. 3. Unused code - methods clearEOF() and setEOF() are never called. 4. Lack of clarity - variable names like f, fp, and eof are not descriptive. 5. Magic numbers - values such as -1 and 0 are used without explanation. 6. Long method - the method is over 20 lines long, which can make it difficult to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | Debug code - commented out code and print statements that are not needed for production2 Inconsistent formatting3 Unused code - methods clearEOF() and setEOF() are never called4 Lack of clarity - variable names like f, fp, and eof are not descriptive5 Magic numbers - values such as - | t | f | f | . Debug code - commented out code and print statements that are not needed for production.2. Inconsistent formatting.3. Unused code - methods clearEOF() and setEOF() are never called.4. Lack of clarity - variable names like f, fp, and eof are not descriptive.5. Magic numbers - values such as - | long method | 0 | 10318 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 1215 | 10318 | minor |
| 2578 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 14936 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 1 | 2578 | 14936 | minor |
| 2561 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14841 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 2 | 2561 | 14841 | minor |
| 372 | public static class MyBigIntArrayList { // TODO private BigInteger[] elems = new BigInteger[100]; private int size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elems.length) { BigInteger[] temp = new BigInteger[size + 10]; for (int i = 0; i < size; i++) { temp[i] = elems[i]; } elems = temp; } else elems[size] = e; } YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy: The "count" variable in the "Value" class is not being used and should be removed. The "elems" array in the "MyBigIntArrayList" class should be declared as final since it is never reassigned. The "add" method in the "MyBigIntArrayList" class can be shortened and simplified. The "temp" variable in the "add" method is unnecessary and can be removed. Magic numbers are present in the code (100 and 10) and should be replaced with named constants. The name of the "add" method is not clear and should be renamed to "addElement". | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | 00]; privateint size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elemslength) { BigInteger[] temp = new BigInteger[size + | t | f | f | 00]; privateint size = 0; public MyBigIntArrayList() { } public void add(BigInteger e) { if (size == elems.length) { BigInteger[] temp = new BigInteger[size + | data class | 0 | 3859 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 372 | 3859 | major |
| 1645 | YES I found bad smells 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LogUtils { private static final String HIVE_L4J = "metastore-log4j2.properties"; private static final Logger l4j = LoggerFactory.getLogger(LogUtils.class); @SuppressWarnings("serial") public static class LogInitializationException extends Exception { LogInitializationException(String msg) { super(msg); } } /** * This is an exception that can be passed to logger just for printing the stacktrace. */ public static class StackTraceLogger extends Exception { public StackTraceLogger(final String msg) { super(msg); } } /** * Initialize log4j. * * @return an message suitable for display to the user * @throws LogInitializationException if log4j fails to initialize correctly */ public static String initHiveLog4j(Configuration conf) throws LogInitializationException { return initHiveLog4jCommon(conf, MetastoreConf.ConfVars.LOG4J_FILE); } private static String initHiveLog4jCommon(Configuration conf, ConfVars confVarName) throws LogInitializationException { if (MetastoreConf.getVar(conf, confVarName).equals("")) { // if log4j configuration file not set, or could not found, use default setting return initHiveLog4jDefault(conf, "", confVarName); } else { // if log4j configuration file found successfully, use HiveConf property value String log4jFileName = MetastoreConf.getVar(conf, confVarName); File log4jConfigFile = new File(log4jFileName); boolean fileExists = log4jConfigFile.exists(); if (!fileExists) { // if property specified file not found in local file system // use default setting return initHiveLog4jDefault( conf, "Not able to find conf file: " + log4jConfigFile, confVarName); } else { // property speficied file found in local file system // use the specified file final boolean async = checkAndSetAsyncLogging(conf); // required for MDC based routing appender so that child threads can inherit the MDC context System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, log4jFileName); logConfigLocation(); return "Logging initialized using configuration in " + log4jConfigFile + " Async: " + async; } } } private static boolean checkAndSetAsyncLogging(final Configuration conf) { final boolean asyncLogging = MetastoreConf.getBoolVar(conf, ConfVars.ASYNC_LOG_ENABLED); if (asyncLogging) { System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); // default is ClassLoaderContextSelector which is created during automatic logging // initialization in a static initialization block. // Changing ContextSelector at runtime requires creating new context factory which will // internally create new context selector based on system property. LogManager.setFactory(new Log4jContextFactory()); } return asyncLogging; } private static String initHiveLog4jDefault(Configuration conf, String logMessage, ConfVars confVarName) throws LogInitializationException { URL hive_l4j = null; switch (confVarName) { case LOG4J_FILE: hive_l4j = LogUtils.class.getClassLoader().getResource(HIVE_L4J); break; default: break; } if (hive_l4j != null) { final boolean async = checkAndSetAsyncLogging(conf); System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, hive_l4j.toString()); logConfigLocation(); return (logMessage + "\n" + "Logging initialized using configuration in " + hive_l4j + " Async: " + async); } else { throw new LogInitializationException( logMessage + "Unable to initialize logging using " + LogUtils.HIVE_L4J + ", not found on CLASSPATH!"); } } private static void logConfigLocation() throws LogInitializationException { // Log a warning if hive-default.xml is found on the classpath if (MetastoreConf.getHiveDefaultLocation() != null) { l4j.warn("DEPRECATED: Ignoring hive-default.xml found on the CLASSPATH at " + MetastoreConf.getHiveDefaultLocation().getPath()); } // Look for hive-site.xml on the CLASSPATH and log its location if found. if (MetastoreConf.getHiveSiteLocation() == null) { l4j.warn("hive-site.xml not found on CLASSPATH"); } else { l4j.debug("Using hive-site.xml found on CLASSPATH at " + MetastoreConf.getHiveSiteLocation().getPath()); } } } |
blob | Long method2 Feature envy3 Duplicate code | t | f | f | . Long method2. Feature envy3. Duplicate code | blob | 0 | 11560 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/LogUtils.java/#L37-L149 | 2 | 1645 | 11560 | minor |
| 161 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": [ "Long method", "Exception handling inconsistency" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | long method, exception handling inconsistency | t | t | f | long method, exception handling inconsistency | feature envy | 0 | 1994 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 2 | 161 | 1994 | minor |
| 1144 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JavadocFormatter { private static final String CODE_RESET = "\033[0m"; private static final String CODE_HIGHLIGHT = "\033[1m"; private static final String CODE_UNDERLINE = "\033[4m"; private final int lineLimit; private final boolean escapeSequencesSupported; /** Construct the formatter. * * @param lineLimit maximum line length * @param escapeSequencesSupported whether escape sequences are supported */ public JavadocFormatter(int lineLimit, boolean escapeSequencesSupported) { this.lineLimit = lineLimit; this.escapeSequencesSupported = escapeSequencesSupported; } private static final int MAX_LINE_LENGTH = 95; private static final int SHORTEST_LINE = 30; private static final int INDENT = 4; /**Format javadoc to plain text. * * @param header element caption that should be used * @param javadoc to format * @return javadoc formatted to plain text */ public String formatJavadoc(String header, String javadoc) { try { StringBuilder result = new StringBuilder(); result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n"); if (javadoc == null) { return result.toString(); } JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null); DocTrees trees = DocTrees.instance(task); DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) { @Override @DefinedBy(Api.COMPILER) public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "" + javadoc + ""; } }); new FormatJavadocScanner(result, task).scan(docComment, null); addNewLineIfNeeded(result); return result.toString(); } catch (URISyntaxException ex) { throw new InternalError("Unexpected exception", ex); } } private class FormatJavadocScanner extends DocTreeScanner { private final StringBuilder result; private final JavacTask task; private int reflownTo; private int indent; private int limit = Math.min(lineLimit, MAX_LINE_LENGTH); private boolean pre; private Map tableColumns; public FormatJavadocScanner(StringBuilder result, JavacTask task) { this.result = result; this.task = task; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitDocComment(DocCommentTree node, Object p) { tableColumns = countTableColumns(node); reflownTo = result.length(); scan(node.getFirstSentence(), p); scan(node.getBody(), p); reflow(result, reflownTo, indent, limit); for (Sections current : docSections.keySet()) { boolean seenAny = false; for (DocTree t : node.getBlockTags()) { if (current.matches(t)) { if (!seenAny) { seenAny = true; if (result.charAt(result.length() - 1) != '\n') result.append("\n"); result.append("\n"); result.append(escape(CODE_UNDERLINE)) .append(docSections.get(current)) .append(escape(CODE_RESET)) .append("\n"); } scan(t, null); } } } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitText(TextTree node, Object p) { String text = node.getBody(); if (!pre) { text = text.replaceAll("[ \t\r\n]+", " ").trim(); if (text.isEmpty()) { text = " "; } } else { text = text.replaceAll("\n", "\n" + indentString(indent)); } result.append(text); return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLink(LinkTree node, Object p) { if (!node.getLabel().isEmpty()) { scan(node.getLabel(), p); } else { result.append(node.getReference().getSignature()); } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitParam(ParamTree node, Object p) { return formatDef(node.getName().getName(), node.getDescription()); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitThrows(ThrowsTree node, Object p) { return formatDef(node.getExceptionName().getSignature(), node.getDescription()); } public Object formatDef(CharSequence name, List description) { result.append(name); result.append(" - "); reflownTo = result.length(); indent = name.length() + 3; if (limit - indent < SHORTEST_LINE) { result.append("\n"); result.append(indentString(INDENT)); indent = INDENT; reflownTo += INDENT; } try { return scan(description, null); } finally { reflow(result, reflownTo, indent, limit); result.append("\n"); } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLiteral(LiteralTree node, Object p) { return scan(node.getBody(), p); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitReturn(ReturnTree node, Object p) { reflownTo = result.length(); try { return super.visitReturn(node, p); } finally { reflow(result, reflownTo, 0, limit); } } Stack listStack = new Stack<>(); Stack defStack = new Stack<>(); Stack tableStack = new Stack<>(); Stack> cellsStack = new Stack<>(); Stack> headerStack = new Stack<>(); @Override @DefinedBy(Api.COMPILER_TREE) public Object visitStartElement(StartElementTree node, Object p) { switch (getHtmlTag(node.getName())) { case P: if (lastNode!= null && lastNode.getKind() == DocTree.Kind.START_ELEMENT && HtmlTag.get(((StartElementTree) lastNode).getName()) == HtmlTag.LI) { //ignore break; } reflowTillNow(); addNewLineIfNeeded(result); result.append(indentString(indent)); reflownTo = result.length(); break; case BLOCKQUOTE: reflowTillNow(); indent += INDENT; break; case PRE: reflowTillNow(); pre = true; break; case UL: reflowTillNow(); listStack.push(-1); indent += INDENT; break; case OL: reflowTillNow(); listStack.push(1); indent += INDENT; break; case DL: reflowTillNow(); defStack.push(indent); break; case LI: reflowTillNow(); if (!listStack.empty()) { addNewLineIfNeeded(result); int top = listStack.pop(); if (top == (-1)) { result.append(indentString(indent - 2)); result.append("* "); } else { result.append(indentString(indent - 3)); result.append("" + top++ + ". "); } listStack.push(top); reflownTo = result.length(); } break; case DT: reflowTillNow(); if (!defStack.isEmpty()) { addNewLineIfNeeded(result); indent = defStack.peek(); result.append(escape(CODE_HIGHLIGHT)); } break; case DD: reflowTillNow(); if (!defStack.isEmpty()) { if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } addNewLineIfNeeded(result); indent = defStack.peek() + INDENT; result.append(indentString(indent)); } break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); addNewLineIfNeeded(result); result.append("\n") .append(escape(CODE_UNDERLINE)); reflownTo = result.length(); break; case TABLE: int columns = tableColumns.get(node); if (columns == 0) { break; //broken input } reflowTillNow(); addNewLineIfNeeded(result); reflownTo = result.length(); tableStack.push(limit); limit = (limit - 1) / columns - 3; for (int sep = 0; sep < (limit + 3) * columns + 1; sep++) { result.append("-"); } result.append("\n"); break; case TR: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(node.getName()); } cellsStack.push(new ArrayList<>()); headerStack.push(new ArrayList<>()); break; case TH: case TD: if (cellsStack.isEmpty()) { //broken code break; } reflowTillNow(); result.append("\n"); reflownTo = result.length(); cellsStack.peek().add(result.length()); headerStack.peek().add(HtmlTag.get(node.getName()) == HtmlTag.TH); break; case IMG: for (DocTree attr : node.getAttributes()) { if (attr.getKind() != DocTree.Kind.ATTRIBUTE) { continue; } AttributeTree at = (AttributeTree) attr; if ("alt".equals(StringUtils.toLowerCase(at.getName().toString()))) { addSpaceIfNeeded(result); scan(at.getValue(), null); addSpaceIfNeeded(result); break; } } break; default: addSpaceIfNeeded(result); break; } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEndElement(EndElementTree node, Object p) { handleEndElement(node.getName()); return super.visitEndElement(node, p); } private void handleEndElement(Name name) { switch (getHtmlTag(name)) { case BLOCKQUOTE: indent -= INDENT; break; case PRE: pre = false; addNewLineIfNeeded(result); reflownTo = result.length(); break; case UL: case OL: if (listStack.isEmpty()) { //ignore stray closing tag break; } reflowTillNow(); listStack.pop(); indent -= INDENT; addNewLineIfNeeded(result); break; case DL: if (defStack.isEmpty()) {//ignore stray closing tag break; } reflowTillNow(); if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } indent = defStack.pop(); addNewLineIfNeeded(result); break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); result.append(escape(CODE_RESET)) .append("\n"); reflownTo = result.length(); break; case TABLE: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(task.getElements().getName("tr")); } if (tableStack.isEmpty()) { break; } limit = tableStack.pop(); break; case TR: if (cellsStack.isEmpty()) { break; } reflowTillNow(); List cells = cellsStack.pop(); List headerFlags = headerStack.pop(); List content = new ArrayList<>(); int maxLines = 0; result.append("\n"); while (!cells.isEmpty()) { int currentCell = cells.remove(cells.size() - 1); String[] lines = result.substring(currentCell, result.length()).split("\n"); result.delete(currentCell - 1, result.length()); content.add(lines); maxLines = Math.max(maxLines, lines.length); } Collections.reverse(content); for (int line = 0; line < maxLines; line++) { for (int column = 0; column < content.size(); column++) { String[] lines = content.get(column); String currentLine = line < lines.length ? lines[line] : ""; result.append("| "); boolean header = headerFlags.get(column); if (header) { result.append(escape(CODE_HIGHLIGHT)); } result.append(currentLine); if (header) { result.append(escape(CODE_RESET)); } int padding = limit - currentLine.length(); if (padding > 0) result.append(indentString(padding)); result.append(" "); } result.append("|\n"); } for (int sep = 0; sep < (limit + 3) * content.size() + 1; sep++) { result.append("-"); } result.append("\n"); reflownTo = result.length(); break; case TD: case TH: break; default: addSpaceIfNeeded(result); break; } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEntity(EntityTree node, Object p) { String name = node.getName().toString(); int code = -1; if (name.startsWith("#")) { try { int v = StringUtils.toLowerCase(name).startsWith("#x") ? Integer.parseInt(name.substring(2), 16) : Integer.parseInt(name.substring(1), 10); if (Entity.isValid(v)) { code = v; } } catch (NumberFormatException ex) { //ignore } } else { Entity entity = Entity.get(name); if (entity != null) { code = entity.code; } } if (code != (-1)) { result.appendCodePoint(code); } else { result.append(node.toString()); } return super.visitEntity(node, p); } private DocTree lastNode; @Override @DefinedBy(Api.COMPILER_TREE) public Object scan(DocTree node, Object p) { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } try { return super.scan(node, p); } finally { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } lastNode = node; } } private void reflowTillNow() { while (result.length() > 0 && result.charAt(result.length() - 1) == ' ') result.delete(result.length() - 1, result.length()); reflow(result, reflownTo, indent, limit); reflownTo = result.length(); } }; private String escape(String sequence) { return this.escapeSequencesSupported ? sequence : ""; } private static final Map docSections = new LinkedHashMap<>(); static { ResourceBundle bundle = ResourceBundle.getBundle("jdk.internal.shellsupport.doc.resources.javadocformatter"); docSections.put(Sections.TYPE_PARAMS, bundle.getString("CAP_TypeParameters")); docSections.put(Sections.PARAMS, bundle.getString("CAP_Parameters")); docSections.put(Sections.RETURNS, bundle.getString("CAP_Returns")); docSections.put(Sections.THROWS, bundle.getString("CAP_Thrown_Exceptions")); } private static String indentString(int indent) { char[] content = new char[indent]; Arrays.fill(content, ' '); return new String(content); } private static void reflow(StringBuilder text, int from, int indent, int limit) { int lineStart = from; while (lineStart > 0 && text.charAt(lineStart - 1) != '\n') { lineStart--; } int lineChars = from - lineStart; int pointer = from; int lastSpace = -1; while (pointer < text.length()) { if (text.charAt(pointer) == ' ') lastSpace = pointer; if (lineChars >= limit) { if (lastSpace != (-1)) { text.setCharAt(lastSpace, '\n'); text.insert(lastSpace + 1, indentString(indent)); lineChars = indent + pointer - lastSpace - 1; pointer += indent; lastSpace = -1; } } lineChars++; pointer++; } } private static void addNewLineIfNeeded(StringBuilder text) { if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') { text.append("\n"); } } private static void addSpaceIfNeeded(StringBuilder text) { if (text.length() == 0) return ; char last = text.charAt(text.length() - 1); if (last != ' ' && last != '\n') { text.append(" "); } } private static HtmlTag getHtmlTag(Name name) { HtmlTag tag = HtmlTag.get(name); return tag != null ? tag : HtmlTag.HTML; //using HtmlTag.HTML as default no-op value } private static Map countTableColumns(DocCommentTree dct) { Map result = new IdentityHashMap<>(); new DocTreeScanner() { private StartElementTree currentTable; private int currentMaxColumns; private int currentRowColumns; @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { switch (getHtmlTag(node.getName())) { case TABLE: currentTable = node; break; case TR: currentMaxColumns = Math.max(currentMaxColumns, currentRowColumns); currentRowColumns = 0; break; case TD: case TH: currentRowColumns++; break; } return super.visitStartElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitEndElement(EndElementTree node, Void p) { if (HtmlTag.get(node.getName()) == HtmlTag.TABLE) { closeTable(); } return super.visitEndElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitDocComment(DocCommentTree node, Void p) { try { return super.visitDocComment(node, p); } finally { closeTable(); } } private void closeTable() { if (currentTable != null) { result.put(currentTable, Math.max(currentMaxColumns, currentRowColumns)); currentTable = null; } } }.scan(dct, null); return result; } private enum Sections { TYPE_PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && ((ParamTree) t).isTypeParameter(); } }, PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && !((ParamTree) t).isTypeParameter(); } }, RETURNS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.RETURN; } }, THROWS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.THROWS; } }; public abstract boolean matches(DocTree t); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 10107 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java/#L70-L712 | 2 | 1144 | 10107 | critical |
| 2201 | { private int[][] data; public ArrayImageSource( int[][] data ) { super( data[ 0 ].length, data.length ); this.data = data; YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13502 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 2201 | 13502 | major |
| 1685 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11686 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 1685 | 11686 | critical |
| 322 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public MessageReference copy(final Queue queue) { return new MessageReferenceImpl(this, queue); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3309 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java/#L137-L140 | 1 | 322 | 3309 | major |
| 2602 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | Long Method"} | t | f | f | . Long Method"} | blob | 0 | 15022 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 1 | 2602 | 15022 | minor |
| 1035 | of the bad smells are present in the code. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 1035 | 9397 | minor | ||
| 65 | { "NO, I did not find any bad smell": "" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | ""} | f | f | f | ""} | blob | 0 | 1073 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 1 | 65 | 1073 | minor |
| 2628 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1() { return cGroup_1; } //( public Group getGroup_1_0() { return cGroup_1_0; } //(={BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0_0() { return cGroup_1_0_0; } //{BinaryLogicalExpression.lhs=current} public Action getBinaryLogicalExpressionLhsAction_1_0_0_0() { return cBinaryLogicalExpressionLhsAction_1_0_0_0; } //op=LogicalANDOperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //LogicalANDOperator public RuleCall getOpLogicalANDOperatorParserRuleCall_1_0_0_1_0() { return cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseORExpression public RuleCall getRhsBitwiseORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseORExpressionParserRuleCall_1_1_0; } @Override public ParserRule getRule() { return rule; } //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)*; YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Unused code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 15087 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 2628 | 15087 | minor |
| 1158 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10145 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 2 | 1158 | 10145 | minor |
| 893 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeleteIndexAction implements ExpirationAction { private static final Logger logger = LoggerFactory.getLogger(DeleteIndexAction.class); private final PersistentProvenanceRepository repository; private final IndexConfiguration indexConfiguration; private final IndexManager indexManager; public DeleteIndexAction(final PersistentProvenanceRepository repo, final IndexConfiguration indexConfiguration, final IndexManager indexManager) { this.repository = repo; this.indexConfiguration = indexConfiguration; this.indexManager = indexManager; } @Override public File execute(final File expiredFile) throws IOException { // count the number of records and determine the max event id that we are deleting. final long numDeleted = 0; long maxEventId = -1L; try (final RecordReader reader = RecordReaders.newRecordReader(expiredFile, repository.getAllLogFiles(), Integer.MAX_VALUE)) { maxEventId = reader.getMaxEventId(); } catch (final IOException ioe) { logger.warn("Failed to obtain max ID present in journal file {}", expiredFile.getAbsolutePath()); } // remove the records from the index final List indexDirs = indexConfiguration.getIndexDirectories(expiredFile); for (final File indexingDirectory : indexDirs) { final Term term = new Term(FieldNames.STORAGE_FILENAME, LuceneUtil.substringBefore(expiredFile.getName(), ".")); boolean deleteDir = false; final EventIndexWriter writer = indexManager.borrowIndexWriter(indexingDirectory); try { final IndexWriter indexWriter = writer.getIndexWriter(); indexWriter.deleteDocuments(term); indexWriter.commit(); final int docsLeft = indexWriter.numDocs(); deleteDir = docsLeft <= 0; logger.debug("After expiring {}, there are {} docs left for index {}", expiredFile, docsLeft, indexingDirectory); } finally { indexManager.returnIndexWriter(writer); } // we've confirmed that all documents have been removed. Delete the index directory. if (deleteDir) { indexManager.removeIndex(indexingDirectory); indexConfiguration.removeIndexDirectory(indexingDirectory); deleteDirectory(indexingDirectory); logger.info("Removed empty index directory {}", indexingDirectory); } } // Update the minimum index to 1 more than the max Event ID in this file. if (maxEventId > -1L) { indexConfiguration.setMinIdIndexed(maxEventId + 1L); } logger.info("Deleted Indices for Expired Provenance File {} from {} index files; {} documents removed", expiredFile, indexDirs.size(), numDeleted); return expiredFile; } private void deleteDirectory(final File dir) { if (dir == null || !dir.exists()) { return; } final File[] children = dir.listFiles(); if (children == null) { return; } for (final File child : children) { if (child.isDirectory()) { deleteDirectory(child); } else if (!child.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", child.getAbsolutePath()); } } if (!dir.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", dir); } } @Override public boolean hasBeenPerformed(final File expiredFile) throws IOException { return false; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8108 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-provenance-repository-bundle/nifi-persistent-provenance-repository/src/main/java/org/apache/nifi/provenance/lucene/DeleteIndexAction.java/#L34-L122 | 2 | 893 | 8108 | major |
| 497 | public class ModifierOp extends BasicOperation {ModifierOp(int type) { super(type); }CODE NOT FOUND YES I found bad smells the bad smells are: 1. Non-descriptive variable names (v1, v2) 2. Multiple parameters for constructor 3. Duplication of super constructor call in child constructor 4. Getter methods returning the values of private variables, instead of methods in the class that manipulates those variables 5. Misplaced and irrelevant comments 6. Inconsistent indentation and formatting 7. Unused and redundant code (ModifierOp constructor with no body) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | Non-descriptive variable names (v | t | f | f | . Non-descriptive variable names (v | data class | 0 | 5043 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 2 | 497 | 5043 | major |
| 1112 | YES, I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 9894 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 2 | 1112 | 9894 | minor |
| 1628 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy 3. Useless comments (SerialVersionUID) 4. Magic numbers (4247427179764560935L) 5. Inconsistent variable naming 6. Use of @JsonProperty annotations instead of proper naming convention 7. Lack of constructor overloading for different parameter types (e.g. int id, String username) 8. Inconsistent getter and setter methods (e.g. getEmail() and setEmail()) 9. Incomplete and inconsistent use of generics in Lists and Maps 10. Use of toStringHelper method instead of a proper toString method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
blob | Long method2 Feature Envy 3 Useless comments (SerialVersionUID)4 Magic numbers (4247427 | t | f | f | . Long method2. Feature Envy 3. Useless comments (SerialVersionUID)4. Magic numbers (4247427 | blob | 0 | 11502 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 1628 | 11502 | minor |
| 1911 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12400 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 1911 | 12400 | minor |
| 3367 | I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 6393 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 3367 | 6393 | minor | ||
| 905 | SequenceFileReader YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SequenceFileReader extends AbstractFileReader { public static final String[] defaultFields = { "key", "value" }; public static final String BUFFER_SIZE = "hdfsspout.reader.buffer.bytes"; private static final Logger LOG = LoggerFactory .getLogger(SequenceFileReader.class); private static final int DEFAULT_BUFF_SIZE = 4096; private final SequenceFile.Reader reader; private final SequenceFileReader.Offset offset; private final Key key; private final Value value; public SequenceFileReader(FileSystem fs, Path file, Map conf) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); this.offset = new SequenceFileReader.Offset(0, 0, 0); } public SequenceFileReader(FileSystem fs, Path file, Map conf, String offset) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.offset = new SequenceFileReader.Offset(offset); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); skipToOffset(this.reader, this.offset, this.key); } private static void skipToOffset(SequenceFile.Reader reader, Offset offset, K key) throws IOException { reader.sync(offset.lastSyncPoint); for (int i = 0; i < offset.recordsSinceLastSync; ++i) { reader.next(key); } } public List next() throws IOException, ParseException { if (reader.next(key, value)) { ArrayList result = new ArrayList(2); Collections.addAll(result, key, value); offset.increment(reader.syncSeen(), reader.getPosition()); return result; } return null; } @Override public void close() { try { reader.close(); } catch (IOException e) { LOG.warn("Ignoring error when closing file " + getFilePath(), e); } } public Offset getFileOffset() { return offset; } public static class Offset implements FileOffset { public long lastSyncPoint; public long recordsSinceLastSync; public long currentRecord; private long currRecordEndOffset; private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if (offset == null) { throw new IllegalArgumentException("offset cannot be null"); } if (offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if (rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord + 1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if (currentRecord < rhs.currentRecord) { return -1; } if (currentRecord == rhs.currentRecord) { return 0; } return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Offset)) { return false; } Offset offset = (Offset) o; return currentRecord == offset.currentRecord; } @Override public int hashCode() { return (int) (currentRecord ^ (currentRecord >>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if (!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 8183 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/SequenceFileReader.java/#L28-L209 | 2 | 905 | 8183 | minor |
| 808 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ScriptValueImpl extends ActionValueImpl implements ScriptValue { /** * The default value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected static final String SCRIPT_EDEFAULT = null; /** * The cached value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected String script = SCRIPT_EDEFAULT; /** * * @generated */ protected ScriptValueImpl( ) { super( ); } /** * * @generated */ @Override protected EClass eStaticClass( ) { return AttributePackage.Literals.SCRIPT_VALUE; } /** * * @generated */ public String getScript( ) { return script; } /** * * @generated */ public void setScript( String newScript ) { String oldScript = script; script = newScript; if ( eNotificationRequired( ) ) eNotify( new ENotificationImpl( this, Notification.SET, AttributePackage.SCRIPT_VALUE__SCRIPT, oldScript, script ) ); } /** * * * @generated */ @Override public Object eGet( int featureID, boolean resolve, boolean coreType ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return getScript( ); } return super.eGet( featureID, resolve, coreType ); } /** * * * @generated */ @Override public void eSet( int featureID, Object newValue ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( (String) newValue ); return; } super.eSet( featureID, newValue ); } /** * * * @generated */ @Override public void eUnset( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( SCRIPT_EDEFAULT ); return; } super.eUnset( featureID ); } /** * * * @generated */ @Override public boolean eIsSet( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return SCRIPT_EDEFAULT == null ? script != null : !SCRIPT_EDEFAULT.equals( script ); } return super.eIsSet( featureID ); } /** * * @generated */ @Override public String toString( ) { if ( eIsProxy( ) ) return super.toString( ); StringBuffer result = new StringBuffer( super.toString( ) ); result.append( " (script: " ); //$NON-NLS-1$ result.append( script ); result.append( ')' ); return result.toString( ); } /** * A convenience method provided to build a script action value when needed * * @param script * @return */ public static final ScriptValue create( String script ) { ScriptValue sv = AttributeFactory.eINSTANCE.createScriptValue( ); sv.setScript( script ); return sv; } /** * A convenient method to get an instance copy. This is much faster than the * ECoreUtil.copy(). */ public ScriptValue copyInstance( ) { ScriptValueImpl dest = new ScriptValueImpl( ); dest.set( this ); return dest; } protected void set( ScriptValue src ) { super.set( src ); script = src.getScript( ); } /* * Get script expression. * * @return expression the script expression. */ public ScriptExpression getScriptExpression( ) { ScriptExpression expression = new ScriptExpression( ); expression.setType( ChartUtil.getExpressionType( script ) ); expression.setValue( ChartUtil.getExpressionText( script ) ); return expression; } /* * Set script expression. * * @param expression the script expression. */ public void setScriptExpression( ScriptExpression expression ) { setScript( ChartUtil.adaptExpression( expression ) ); } } // ScriptValueImpl |
blob | data class | t | t | f | data class | blob | 0 | 7627 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/model/attribute/impl/ScriptValueImpl.java/#L35-L237 | 1 | 808 | 7627 | minor |
| 417 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 4230 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 417 | 4230 | major |
| 1299 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10640 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 1299 | 10640 | major |
| 1690 | {"response": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11702 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 1 | 1690 | 11702 | minor |
| 457 | {"response": "YES, I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | blob | t | t | f | blob | data class | 0 | 4454 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 457 | 4454 | minor |
| 2147 | {"error": "Sorry, I am unable to provide direct code analysis or execution. However, I can help guide you on how to identify common code smells in Java code by providing descriptions and examples. Let me know if you need any information."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | f | f | f | data class | 0 | 13277 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 2147 | 13277 | major | ||
| 1339 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class DFA28 extends DFA { public DFA28(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 28; this.eot = dfa_9; this.eof = dfa_21; this.min = dfa_10; this.max = dfa_11; this.accept = dfa_12; this.special = dfa_13; this.transition = dfa_14; } public String getDescription() { return "4005:2: ( rule__Object__UnorderedGroup_5__5 )?"; } public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_0 = input.LA(1); int index28_0 = input.index(); input.rewind(); s = -1; if ( LA28_0 == 19 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 0) ) {s = 1;} else if ( LA28_0 == 20 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 1) ) {s = 2;} else if ( LA28_0 == 21 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 2) ) {s = 3;} else if ( LA28_0 == 33 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 3) ) {s = 4;} else if ( LA28_0 == 26 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 5;} else if ( LA28_0 == 27 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 6;} else if ( LA28_0 == 22 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 5) ) {s = 7;} else if ( LA28_0 == 24 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 6) ) {s = 8;} else if ( LA28_0 == 25 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 7) ) {s = 9;} else if ( (LA28_0==EOF||LA28_0==17) ) {s = 10;} input.seek(index28_0); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10738 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/ide/contentassist/antlr/internal/InternalBug304681TestLanguageParser.java/#L20062-L20120 | 1 | 1339 | 10738 | major |
| 821 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy. | data class | 0 | 7686 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 821 | 7686 | major |
| 599 | YES I found bad smells the bad smells are: 1. Empty class 2. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Empty class2 Primitive obsession | t | f | f | . Empty class2. Primitive obsession | data class | 0 | 5988 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 599 | 5988 | minor |
| 539 | ] 502.Bad comments 507.Long class 510.Duplicate code 511.Unused code 514.Magic numbers 516.Method chaining 518.Lazy class 520.Long parameter list 522.Data class 525.God class 526.Lazy initialization 529.Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
data class | 0Duplicate code5 | f | f | f | 0.Duplicate code5 | data class | 0 | 5502 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 2 | 539 | 5502 | minor |
| 1007 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9259 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1007 | 9259 | minor |
| 2513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14690 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 2513 | 14690 | minor |
| 1820 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class HttpsTokenInInterceptor extends AbstractPhaseInterceptor { HttpsTokenInInterceptor() { super(Phase.PRE_STREAM); addBefore(WSS4JStaxInInterceptor.class.getName()); } public void handleMessage(Message message) throws Fault { AssertionInfoMap aim = message.get(AssertionInfoMap.class); // extract Assertion information if (aim != null) { Collection ais = PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.HTTPS_TOKEN); boolean requestor = isRequestor(message); if (ais.isEmpty()) { if (!requestor) { try { assertNonHttpsTransportToken(message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } } return; } if (!requestor) { try { assertHttps(aim, ais, message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } // Store the TLS principal on the message context SecurityContext sc = message.get(SecurityContext.class); if (sc == null || sc.getUserPrincipal() == null) { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null && tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0 && (tlsInfo.getPeerCertificates()[0] instanceof X509Certificate) ) { X509Certificate cert = (X509Certificate)tlsInfo.getPeerCertificates()[0]; message.put( SecurityContext.class, createSecurityContext(cert.getSubjectX500Principal()) ); } } } else { //client side should be checked on the way out for (AssertionInfo ai : ais) { ai.setAsserted(true); } PolicyUtils.assertPolicy(aim, SPConstants.HTTP_DIGEST_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.HTTP_BASIC_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.REQUIRE_CLIENT_CERTIFICATE); } } } private void assertHttps( AssertionInfoMap aim, Collection ais, Message message ) throws XMLSecurityException { List securityEvents = getSecurityEventList(message); AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); for (AssertionInfo ai : ais) { boolean asserted = true; HttpsToken token = (HttpsToken)ai.getAssertion(); HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); Map> headers = getProtocolHeaders(message); if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpBasicAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Basic")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpBasicAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(true, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_BASIC_AUTHENTICATION)); } } if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpDigestAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Digest")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpDigestAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(false, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_DIGEST_AUTHENTICATION)); } } TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { if (token.getAuthenticationType() == HttpsToken.AuthenticationType.RequireClientCertificate) { if (tlsInfo.getPeerCertificates() == null || tlsInfo.getPeerCertificates().length == 0) { asserted = false; } else { PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.REQUIRE_CLIENT_CERTIFICATE)); } } if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } } else { asserted = false; } ai.setAsserted(asserted); if (asserted) { securityEvents.add(httpsTokenSecurityEvent); } } } // We might have an IssuedToken TransportToken private void assertNonHttpsTransportToken(Message message) throws XMLSecurityException { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } List securityEvents = getSecurityEventList(message); securityEvents.add(httpsTokenSecurityEvent); } } private List getSecurityEventList(Message message) { @SuppressWarnings("unchecked") List securityEvents = (List) message.getExchange().get(SecurityEvent.class.getName() + ".out"); if (securityEvents == null) { securityEvents = new ArrayList<>(); message.getExchange().put(SecurityEvent.class.getName() + ".out", securityEvents); } return securityEvents; } private SecurityContext createSecurityContext(final Principal p) { return new SecurityContext() { public Principal getUserPrincipal() { return p; } public boolean isUserInRole(String role) { return false; } }; } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 12094 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/HttpsTokenInterceptorProvider.java/#L191-L390 | 2 | 1820 | 12094 | major |
| 5128 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14367 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 2 | 5128 | 14367 | minor |
| 5278 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 14761 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 5278 | 14761 | minor |
| 2155 | { "answer": "YES I found bad smells", "bad smells are": ["Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | blob | t | t | f | blob | data class | 0 | 13299 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 1 | 2155 | 13299 | minor |
| 718 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class GenericConnectionStatusHtmlCreator { public static String generateConnectionViewHtml(String providerDisplayName, String providerId, UserProfile profile) { String escProviderDisplayName = escape(providerDisplayName); StringBuilder builder = new StringBuilder(); if (profile == null) { builder.append("Connect to " + escProviderDisplayName + ""); builder.append(""); builder.append(""); builder.append("You aren't connected to "); builder.append(escProviderDisplayName); builder.append(" yet. Click the button to connect with your "); builder.append(escProviderDisplayName); builder.append(" account."); builder.append(""); builder.append("Connect to "); builder.append(escProviderDisplayName); builder.append(""); builder.append(""); } else { String escProfileName = escape(profile.getName()); builder.append("Connected to "); builder.append(escProviderDisplayName); builder.append(""); builder.append("Hello, "); builder.append(escProfileName); builder.append("!You are now connected to "); builder.append(escProviderDisplayName); String username = profile.getUsername(); if (username !=null) { builder.append(" as "); builder.append(escape(username)); } builder.append("."); } return builder.toString(); } private static String escape(String in) { return htmlEscape(in).replaceAll("\\{", "{").replaceAll("\\}", "}"); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6828 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-web/src/main/java/org/springframework/social/connect/web/GenericConnectionStatusView.java/#L91-L138 | 1 | 718 | 6828 | minor |
| 638 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6319 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 | 1 | 638 | 6319 | major |
| 3801 | { "input_code": "public class Calculator { public int add(int num1, int num2) { int sum = num1 + num2; return sum; } public int multiply(int num1, int num2) { int product = num1 * num2; return product; }}", "code_smells_to_check": ["Blob", "Data Class", "Feature Envy", "Long Method"], "identified_bad_smells": { "detected": false } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | detected: false | t | t | f | detected: false | feature envy | 0 | 9635 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1280-L1292 | 1 | 3801 | 9635 | minor |
| 92 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @NbBundle.Messages({ "LocksFeatureUI_show=View by:", "LocksFeatureUI_aggregationByThreads=Threads", "LocksFeatureUI_aggregationByMonitors=Monitors", "LocksFeatureUI_aggregationHint=Results aggregation" }) abstract class LocksFeatureUI extends FeatureUI { private ProfilerToolbar toolbar; private LockContentionPanel locksView; // --- External implementation --------------------------------------------- abstract ProfilerClient getProfilerClient(); abstract void refreshResults(); // --- API implementation -------------------------------------------------- ProfilerToolbar getToolbar() { if (toolbar == null) initUI(); return toolbar; } JPanel getResultsUI() { if (locksView == null) initUI(); return locksView; } void sessionStateChanged(int sessionState) { refreshToolbar(sessionState); if (sessionState == Profiler.PROFILING_INACTIVE || sessionState == Profiler.PROFILING_IN_TRANSITION) { if (locksView != null) locksView.profilingSessionFinished(); } else if (sessionState == Profiler.PROFILING_RUNNING) { if (locksView != null) locksView.profilingSessionStarted(); } } void resetPause() { // if (lrPauseButton != null) lrPauseButton.setSelected(false); } void setForceRefresh() { if (locksView != null) locksView.setForceRefresh(true); } void refreshData() throws ClientUtils.TargetAppOrVMTerminated { if (locksView != null) locksView.refreshData(); } void resetData() { if (locksView != null) locksView.resetData(); } // --- UI ------------------------------------------------------------------ private JLabel shLabel; private ActionPopupButton shAggregation; private void initUI() { assert SwingUtilities.isEventDispatchThread(); // --- Results --------------------------------------------------------- locksView = new LockContentionPanel() { protected ProfilerClient getProfilerClient() { return LocksFeatureUI.this.getProfilerClient(); } }; locksView.lockContentionEnabled(); locksView.putClientProperty("HelpCtx.Key", "ProfileLocks.HelpCtx"); // NOI18N // --- Toolbar --------------------------------------------------------- shLabel = new GrayLabel(Bundle.LocksFeatureUI_show()); Action aThreads = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByThreads()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_THREADS); } }; Action aMonitors = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByMonitors()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_MONITORS); } }; shAggregation = new ActionPopupButton(aThreads, aMonitors); shAggregation.setToolTipText(Bundle.LocksFeatureUI_aggregationHint()); toolbar = ProfilerToolbar.create(true); toolbar.addSpace(2); toolbar.addSeparator(); toolbar.addSpace(5); toolbar.add(shLabel); toolbar.addSpace(2); toolbar.add(shAggregation); // --- Sync UI --------------------------------------------------------- setAggregation(LockContentionPanel.Aggregation.BY_THREADS); sessionStateChanged(getSessionState()); } private void refreshToolbar(final int state) { // if (toolbar != null) SwingUtilities.invokeLater(new Runnable() { // public void run() { // } // }); } private void setAggregation(LockContentionPanel.Aggregation aggregation) { locksView.setAggregation(aggregation); shAggregation.selectAction(aggregation.ordinal()); } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 1248 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler/src/org/graalvm/visualvm/lib/profiler/v2/features/LocksFeatureUI.java/#L65-L192 | 1 | 92 | 1248 | minor |
| 681 | . NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 6593 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 2 | 681 | 6593 | minor | ||
| 377 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class JsonObjects { private static final Jsonb JSON = JsonbBuilder.create(); private JsonObjects() { } static List getColumns(JsonObject jsonObject) { Map map = JSON.fromJson(jsonObject.toString(), Map.class); return Columns.of(map); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3896 | https://github.com/eclipse/jnosql/blob/9f03fa6ffe2dd4b538f7dbce424649aa4e484657/communication/diana-column/src/main/java/org/jnosql/diana/api/column/query/JsonObjects.java/#L28-L40 | 2 | 377 | 3896 | minor |
| 855 | {"response": "YES I found bad smells 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugTraceBasedRegion extends AbstractTraceRegion { private final DebugTraceRegion delegate; protected DebugTraceBasedRegion(AbstractTraceRegion parent, DebugTraceRegion delegate) { super(parent); this.delegate = delegate; for (DebugTraceRegion child : delegate.getNestedRegions()) new DebugTraceBasedRegion(this, child); } private LocationData convert(DebugLocationData data) { SourceRelativeURI uri = data.getPath() != null ? new SourceRelativeURI(data.getPath()) : null; return new LocationData(data.getOffset(), data.getLength(), data.getLineNumber(), data.getEndLineNumber(), uri); } @Override public List getAssociatedLocations() { List result = Lists.newArrayListWithCapacity(delegate.getAssociations().size()); for (DebugLocationData data : delegate.getAssociations()) result.add(convert(data)); return result; } @Override public SourceRelativeURI getAssociatedSrcRelativePath() { SourceRelativeURI path = super.getAssociatedSrcRelativePath(); if (path != null) return path; return getAssociatedSrcRelativePath(delegate); } protected SourceRelativeURI getAssociatedSrcRelativePath(DebugTraceRegion region) { for (DebugLocationData associated : region.getAssociations()) { URI uri = associated.getPath(); if (uri != null) return new SourceRelativeURI(uri); } EObject container = region.eContainer(); if (container instanceof DebugTraceRegion) return getAssociatedSrcRelativePath((DebugTraceRegion) container); return null; } @Override public int getMyEndLineNumber() { return delegate.getMyEndLineNumber(); } @Override public int getMyLength() { return delegate.getMyLength(); } @Override public int getMyLineNumber() { return delegate.getMyLineNumber(); } @Override public int getMyOffset() { return delegate.getMyOffset(); } @Override public boolean isUseForDebugging() { return delegate.isUseForDebugging(); } } |
data class | Not specified | f | f | f | false | 0 | 7879 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.builder/src/org/eclipse/xtext/builder/trace/DebugTraceBasedRegion.java/#L24-L93 | 1 | 855 | 7879 | major | |
| 2246 | {"response": "YES I found bad smells the bad smells are: Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13649 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 2246 | 13649 | major |
| 1621 | { "message": "YES, I found bad smells", "bad_smells_are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | t | f | f | data class | 0 | 11483 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 1 | 1621 | 11483 | minor | ||
| 2356 | YES, I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 14230 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 2356 | 14230 | critical |
| 1264 | { "result": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10540 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 1 | 1264 | 10540 | minor |
| 2181 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13416 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 2181 | 13416 | minor |
| 2480 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14595 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 2480 | 14595 | major |
| 1447 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. God class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy3 Primitive obsession4 God class | t | f | f | . Long method2. Feature envy3. Primitive obsession4. God class | data class | 0 | 10988 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 1447 | 10988 | minor |
| 1749 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | Blob, Long Method | t | f | f | Blob, Long Method | data class | 0 | 11857 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 1749 | 11857 | critical |
| 452 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static TimeOfYear fromDateTime(DateTime dateTime) { DateTime nextYear = dateTime.plusYears(1); // This turns February 29 into February 28. TimeOfYear instance = new TimeOfYear(); instance.timeString = String.format( "%02d %02d %08d", nextYear.getMonthOfYear(), nextYear.getDayOfMonth(), nextYear.getMillisOfDay()); return instance; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4409 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/common/TimeOfYear.java/#L61-L70 | 1 | 452 | 4409 | minor |
| 4059 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10711 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 | 2 | 4059 | 10711 | minor |
| 166 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({"rawtypes", "unchecked"}) public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler { protected final JMXAgentContext agentContext; protected StandardMBean mbean; protected final AtomicLong trackedId = new AtomicLong(); /** * * @param agentContext * @param filter */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) { super(agentContext.getBundleContext(), filter, null); this.agentContext = agentContext; } /** * * @param agentContext * @param clazz */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) { super(agentContext.getBundleContext(), clazz, null); this.agentContext = agentContext; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Logger logger = agentContext.getLogger(); Object trackedService = null; long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); //API stipulates versions for compendium services with static ObjectName //This shouldn't happen but added as a consistency check if (trackedId.compareAndSet(0, serviceId)) { logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceId + "]"); trackedService = context.getService(reference); mbean = constructInjectMBean(trackedService); agentContext.registerMBean(AbstractCompendiumHandler.this); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed"); } return trackedService; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { Logger logger = agentContext.getLogger(); long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID); if (trackedId.compareAndSet(serviceID, 0)) { logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceID + "]"); agentContext.unregisterMBean(AbstractCompendiumHandler.this); context.ungetService(reference); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed"); } } private String getServiceDescription(ServiceReference reference) { String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION); if (serviceDescription == null) { Object obj = reference.getProperty(Constants.OBJECTCLASS); if (obj instanceof String[]) { StringBuilder sb = new StringBuilder(); for (String s : (String[]) obj) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } serviceDescription = sb.toString(); } else { serviceDescription = obj.toString(); } } return serviceDescription; } /** * Gets the StandardMBean managed by this handler when the backing service is available or null * * @see org.apache.aries.jmx.MBeanHandler#getMbean() */ public StandardMBean getMbean() { return mbean; } /** * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied * service tracked by this handler * * @param targetService * the compendium service tracked by this handler * @return The StandardMBean instance whose registration lifecycle will be managed by this handler */ protected abstract StandardMBean constructInjectMBean(Object targetService); /** * The base name of the MBean. Will be expanded with the framework name and the UUID. * @return */ protected abstract String getBaseName(); /** * @see org.apache.aries.jmx.MBeanHandler#getName() */ public String getName() { return ObjectNameUtils.createFullObjectName(context, getBaseName()); } } |
blob | long method | t | t | f | long method | blob | 0 | 2010 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java/#L43-L166 | 2 | 166 | 2010 | minor |
| 376 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override int recursionUnsafeHashCode() { return System.identityHashCode(this); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3877 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/AllType.java/#L112-L115 | 1 | 376 | 3877 | major |
| 2098 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Insufficient encapsulation 4. Inconsistent formatting 5. Use of magic numbers 6. Duplicate code 7. Inappropriate commenting 8. Inadequate naming 9. Lack of modularity 10. Underuse of abstractions 11. Frequent code changes 12. Poor exception handling 13. Lack of error checking 14. Mixing of concerns 15. Inappropriate levels of abstraction 16. Use of static method 17. Unused variables 18. Confusing variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method2 Feature envy 3 Insufficient encapsulation 4 Inconsistent formatting 5 Use of magic numbers 6 Duplicate code 7 Inappropriate commenting 8 Inadequate naming 9 Lack of modularity | t | f | f | . Long method2. Feature envy 3. Insufficient encapsulation 4. Inconsistent formatting 5. Use of magic numbers 6. Duplicate code 7. Inappropriate commenting 8. Inadequate naming 9. Lack of modularity | data class | 0 | 13153 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 2098 | 13153 | minor |
| 2030 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "3. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | 3. long method | t | t | f | 3. long method | data class | 0 | 12809 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 2030 | 12809 | minor |
| 284 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 3039 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 2 | 284 | 3039 | major |
| 828 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7726 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 1 | 828 | 7726 | major |
| 803 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Region { /** * Gets the region and state machine unique id. * * @return the region and state machine unique id */ UUID getUuid(); /** * Gets the region and state machine id. This identifier * is provided for users disposal and can be set from * a various ways to build a machines. * * @return the region and state machine id */ String getId(); /** * Start the region. */ void start(); /** * Stop the region. */ void stop(); /** * Send an event {@code E} wrapped with a {@link Message} to the region. * * @param event the wrapped event to send * @return true if event was accepted */ boolean sendEvent(Message event); /** * Send an event {@code E} to the region. * * @param event the event to send * @return true if event was accepted */ boolean sendEvent(E event); /** * Gets the current {@link State}. * * @return current state */ State getState(); /** * Gets the {@link State}s defined in this region. Returned collection is * an unmodifiable copy because states in a state machine are immutable. * * @return immutable copy of states */ Collection> getStates(); /** * Gets a {@link Transition}s for this region. * * @return immutable copy of transitions */ Collection> getTransitions(); /** * Checks if region complete. Region is considered to be completed if it has * reached its end state and no further event processing is happening. * * @return true, if complete */ boolean isComplete(); /** * Adds the state listener. * * @param listener the listener */ void addStateListener(StateMachineListener listener); /** * Removes the state listener. * * @param listener the listener */ void removeStateListener(StateMachineListener listener); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 7611 | https://github.com/spring-projects/spring-statemachine/blob/02ecb28751fcffd6f5306189f41bbcadcd3af18a/spring-statemachine-core/src/main/java/org/springframework/statemachine/region/Region.java/#L35-L123 | 1 | 803 | 7611 | major |
| 1448 | Yes I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10989 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 1448 | 10989 | minor |
| 2553 | of the detected bad smells NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14816 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 2 | 2553 | 14816 | minor | ||
| 2202 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
blob | data class | t | t | f | data class | blob | 0 | 13505 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 1 | 2202 | 13505 | major |
| 841 | YES I found bad smells the bad smells are: 1.Long method 2.Magic numbers and strings 3.Duplicate code 4.Inappropriate naming of variables and methods 5.Lack of encapsulation and proper access modifiers 6.Coupling and cohesion issues 7.Nested conditional statements 8.Lack of code comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_LOCATION = 1; private static final String NEARBY_BEACONS_FRAGMENT_TAG = "NearbyBeaconsFragmentTag"; private static final String SETTINGS_FRAGMENT_TAG = "SettingsFragmentTag"; private static final String BLOCKED_URLS_FRAGMENT_TAG = "BlockedUrlsFragmentTag"; private static final String ABOUT_FRAGMENT_TAG = "AboutFragmentTag"; private static final String DEMOS_FRAGMENT_TAG = "DemosFragmentTag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Utils.setSharedPreferencesDefaultValues(this); PermissionCheck.getInstance().setCheckingPermissions(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * Called when a menu item is tapped. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // If the about menu item was selected case R.id.action_about: showAboutFragment(); return true; // If the settings menu item was selected case R.id.action_settings: showSettingsFragment(); return true; case R.id.block_settings: showBlockedFragment(); return true; case R.id.action_demos: showDemosFragment(); return true; // If the action bar up button was pressed case android.R.id.home: getFragmentManager().popBackStack(); getActionBar().setDisplayHomeAsUpEnabled(false); } return super.onOptionsItemSelected(item); } /** * Ensures Bluetooth is available on the beacon and it is enabled. If not, * displays a dialog requesting user permission to enable Bluetooth. */ private void checkPermissions(BluetoothAdapter bluetoothAdapter) { // Acquire lock PermissionCheck.getInstance().setCheckingPermissions(true); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } ensureLocationPermissionIsEnabled(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == REQUEST_ENABLE_BT && resultCode == -1) { ensureLocationPermissionIsEnabled(); return; } Toast.makeText(this, getString(R.string.bt_on), Toast.LENGTH_LONG).show(); finish(); } private void ensureLocationPermissionIsEnabled() { if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } PermissionCheck.getInstance().setCheckingPermissions(false); finishLoad(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionCheck.getInstance().setCheckingPermissions(false); } else { Toast.makeText(getApplicationContext(), getString(R.string.loc_permission), Toast.LENGTH_LONG).show(); finish(); } break; } default: } } @Override protected void onResume() { super.onResume(); // Lock to prevent onResume from running until all permissions are granted if (!PermissionCheck.getInstance().isCheckingPermissions()) { Log.d(TAG, "resumed MainActivity"); BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = btManager != null ? btManager.getAdapter() : null; if (btAdapter == null) { Toast.makeText(getApplicationContext(), R.string.error_bluetooth_support, Toast.LENGTH_LONG).show(); finish(); return; } if (Utils.checkIfUserHasOptedIn(this)) { Log.d(TAG, "checkingPermissions"); checkPermissions(btAdapter); } else { // Show the oob activity Intent intent = new Intent(this, OobActivity.class); startActivity(intent); } } } private void finishLoad() { Intent intent = new Intent(this, ScreenListenerService.class); startService(intent); NearbyBeaconsFragment nearbyBeaconsFragment = (NearbyBeaconsFragment) getFragmentManager().findFragmentByTag(NEARBY_BEACONS_FRAGMENT_TAG); if (nearbyBeaconsFragment != null) { nearbyBeaconsFragment.restartScan(); } else { showFragment(new NearbyBeaconsFragment(), NEARBY_BEACONS_FRAGMENT_TAG, false); } } /** * Show the fragment to configure the app. */ private void showSettingsFragment() { showFragment(new SettingsFragment(), SETTINGS_FRAGMENT_TAG, true); } /** * Show the fragment displaying information about this application. */ private void showAboutFragment() { showFragment(new AboutFragment(), ABOUT_FRAGMENT_TAG, true); } /** * Show the fragment displaying the blocked URLs. */ private void showBlockedFragment() { showFragment(new BlockedFragment(), BLOCKED_URLS_FRAGMENT_TAG, true); } /** * Show the fragment displaying the demos. */ private void showDemosFragment() { showFragment(new DemosFragment(), DEMOS_FRAGMENT_TAG, true); } @SuppressLint("CommitTransaction") private void showFragment(Fragment newFragment, String fragmentTag, boolean addToBackStack) { FragmentTransaction transaction = getFragmentManager().beginTransaction() .setCustomAnimations( R.animator.fade_in_and_slide_up_fragment, R.animator.fade_out_fragment, R.animator.fade_in_activity, R.animator.fade_out_fragment) .replace(R.id.main_activity_container, newFragment, fragmentTag); if (addToBackStack) { transaction.addToBackStack(null); } transaction.commit(); } } |
blob | Long method2Magic numbers and strings3Duplicate code4Inappropriate naming of variables and methods5Lack of encapsulation and proper access modifiers6Coupling and cohesion issues7Nested conditional statements8Lack of code comments and documentation | t | f | f | .Long method2.Magic numbers and strings3.Duplicate code4.Inappropriate naming of variables and methods5.Lack of encapsulation and proper access modifiers6.Coupling and cohesion issues7.Nested conditional statements8.Lack of code comments and documentation. | blob | 0 | 7797 | https://github.com/google/physical-web/blob/12604319e99b6d6dff451fc5a58a13a271f1dc7a/android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/MainActivity.java/#L39-L228 | 2 | 841 | 7797 | major |
| 304 | YES I found bad smells the bad smells are: 1.Magic number, 2.Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Magic number, 2Duplicate code | t | f | f | .Magic number, 2.Duplicate code | data class | 0 | 3183 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 304 | 3183 | major |
| 2689 | { "message": "YES I found bad smells" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 15284 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 2689 | 15284 | major |
| 278 | {"input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example {\n private int number;\n public Example(int number) {\n this.number = number;\n }\n public int calculateSquare() {\n return this.number * this.number;\n }\n}" }} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | Not specified | f | f | f | Data Class, Feature Envy, Long Method | false | 0 | 2984 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 1 | 278 | 2984 | minor |
| 175 | { "output": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Duplicate code", "3. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | 1. long method, 2. duplicate code, 3. feature envy | t | t | f | 1. long method, 2. duplicate code, 3. feature envy | data class | 0 | 2046 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 175 | 2046 | major |
| 459 | {"answer": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 4459 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 459 | 4459 | minor |
| 85 | { "response": "YES I found bad smells the bad smells are: 1.Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Step deleteJobAsync( String name, String namespace, V1DeleteOptions deleteOptions, ResponseStep responseStep) { return createRequestAsync( responseStep, new RequestParams("deleteJob", namespace, name, deleteOptions), DELETE_JOB); } |
feature envy | Not specified | f | f | f | false | 0 | 1212 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L991-L998 | 2 | 85 | 1212 | minor | |
| 2578 | YES I found bad smells. 1. Long method 2. Feature envy (some methods are using entities from different classes heavily) 3. Too many dependencies and injections 4. Use of "ToDo" comments 5. Multiple responsibilities and roles for the class 6. Unclear naming conventions for variables and methods 7. Use of magic numbers and strings 8. Use of deprecated methods and classes 9. Code duplication 10. High coupling and low cohesion 11. Poor exception handling 12. Lack of proper comments and documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | Long method2 Feature envy (some methods are using entities from different classes heavily)3 Too many dependencies and injections4 Use of "ToDo" comments5 Multiple responsibilities and roles for the class6 Unclear naming conventions for variables and methods7 Use of magic numbers and strings8 Use of deprecated methods and classes9 Code duplication | t | f | f | . Long method2. Feature envy (some methods are using entities from different classes heavily)3. Too many dependencies and injections4. Use of "ToDo" comments5. Multiple responsibilities and roles for the class6. Unclear naming conventions for variables and methods7. Use of magic numbers and strings8. Use of deprecated methods and classes9. Code duplication | blob | 0 | 14936 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 2 | 2578 | 14936 | minor |
| 2038 | Yes, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12843 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 2038 | 12843 | minor |
| 331 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Expression setUpper(Bound newUpper) { upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive); return this; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 3397 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/index/sasi/plan/Expression.java/#L127-L131 | 2 | 331 | 3397 | minor |
| 18 | {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 660 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 | 1 | 18 | 660 | critical |
| 1241 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10410 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 1241 | 10410 | major |
| 46 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public UDATA add(UDATA parameter) { return new UDATA(this).add(parameter); } |
feature envy | blob | t | t | f | blob | feature envy | 0 | 835 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/types/U32.java/#L70-L72 | 1 | 46 | 835 | minor |
| 540 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long method2 Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | t | f | f | . Long method2. Primitive obsession (using primitive types for non-trivial data, such as Boolean and String) | data class | 0 | 5535 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 540 | 5535 | major |
| 2320 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data clumps 4. Duplicate code 5. Inappropriate comment 6. Cyclic complexity 7. Mutable data 8. Magic number 9. Dead code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WordMedian extends Configured implements Tool { private double median = 0; private final static IntWritable ONE = new IntWritable(1); /** * Maps words from line of text into a key-value pair; the length of the word * as the key, and 1 as the value. */ public static class WordMedianMapper extends Mapper { private IntWritable length = new IntWritable(); /** * Emits a key-value pair for counting the word. Outputs are (IntWritable, * IntWritable). * * @param value * This will be a line of text coming in from our input file. */ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { String string = itr.nextToken(); length.set(string.length()); context.write(length, ONE); } } } /** * Performs integer summation of all the values for each key. */ public static class WordMedianReducer extends Reducer { private IntWritable val = new IntWritable(); /** * Sums all the individual values within the iterator and writes them to the * same key. * * @param key * This will be a length of a word that was read. * @param values * This will be an iterator of all the values associated with that * key. */ public void reduce(IntWritable key, Iterable values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } val.set(sum); context.write(key, val); } } /** * This is a standard program to read and find a median value based on a file * of word counts such as: 1 456, 2 132, 3 56... Where the first values are * the word lengths and the following values are the number of times that * words of that length appear. * * @param path * The path to read the HDFS file from (part-r-00000...00001...etc). * @param medianIndex1 * The first length value to look for. * @param medianIndex2 * The second length value to look for (will be the same as the first * if there are an even number of words total). * @throws IOException * If file cannot be found, we throw an exception. * */ private double readAndFindMedian(String path, int medianIndex1, int medianIndex2, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); Path file = new Path(path, "part-r-00000"); if (!fs.exists(file)) throw new IOException("Output not found!"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8)); int num = 0; String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); // grab length String currLen = st.nextToken(); // grab count String lengthFreq = st.nextToken(); int prevNum = num; num += Integer.parseInt(lengthFreq); if (medianIndex2 >= prevNum && medianIndex1 <= num) { System.out.println("The median is: " + currLen); br.close(); return Double.parseDouble(currLen); } else if (medianIndex2 >= prevNum && medianIndex1 < num) { String nextCurrLen = st.nextToken(); double theMedian = (Integer.parseInt(currLen) + Integer .parseInt(nextCurrLen)) / 2.0; System.out.println("The median is: " + theMedian); br.close(); return theMedian; } } } finally { if (br != null) { br.close(); } } // error, no median found return -1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new WordMedian(), args); } @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: wordmedian "); return 0; } setConf(new Configuration()); Configuration conf = getConf(); @SuppressWarnings("deprecation") Job job = new Job(conf, "word median"); job.setJarByClass(WordMedian.class); job.setMapperClass(WordMedianMapper.class); job.setCombinerClass(WordMedianReducer.class); job.setReducerClass(WordMedianReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean result = job.waitForCompletion(true); // Wait for JOB 1 -- get middle value to check for Median long totalWords = job.getCounters() .getGroup(TaskCounter.class.getCanonicalName()) .findCounter("MAP_OUTPUT_RECORDS", "Map output records").getValue(); int medianIndex1 = (int) Math.ceil((totalWords / 2.0)); int medianIndex2 = (int) Math.floor((totalWords / 2.0)); median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf); return (result ? 0 : 1); } public double getMedian() { return median; } } |
blob | Long method2 Feature envy3 Data clumps4 Duplicate code5 Inappropriate comment6 Cyclic complexity7 Mutable data8 Magic number9 Dead code | t | f | f | . Long method2. Feature envy3. Data clumps4. Duplicate code5. Inappropriate comment6. Cyclic complexity7. Mutable data8. Magic number9. Dead code | blob | 0 | 14128 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/WordMedian.java/#L43-L212 | 2 | 2320 | 14128 | minor |
| 826 | YES I found bad smells the bad smells are: Naming, Long method, Duplicated code, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component @Reference(name = "shell", strategy = ReferenceStrategy.EVENT, policy = ReferencePolicy.DYNAMIC, referenceInterface = Shell.class, cardinality = ReferenceCardinality.OPTIONAL_UNARY) public class JdkDelegatingLogListener extends AbstractFlashingObject implements LogListener { public static final String DO_NOT_LOG = "#DO_NOT_LOG"; private final static Logger LOGGER = HandlerUtils.getLogger(JdkDelegatingLogListener.class); @Reference(policy = ReferencePolicy.DYNAMIC) private volatile LogReaderService logReaderService; public static String cleanThrowable(final Throwable throwable) { final StringBuilder result = new StringBuilder(); result.append(LINE_SEPARATOR); result.append(throwable.toString().replace(DO_NOT_LOG, "")); result.append(LINE_SEPARATOR); for (final StackTraceElement ste : throwable.getStackTrace()) { result.append(ste); result.append(LINE_SEPARATOR); } return result.toString(); } @SuppressWarnings("unchecked") protected void activate(final ComponentContext context) { logReaderService.addLogListener(this); final Enumeration latestLogs = logReaderService.getLog(); if (latestLogs.hasMoreElements()) { logNow(latestLogs.nextElement(), false); } } private String buildMessage(final LogEntry entry) { final StringBuilder sb = new StringBuilder(); sb.append("[").append(entry.getBundle()).append("] ").append(entry.getMessage()); return sb.toString(); } private boolean containsDoNotLogTag(final Throwable throwable) { if (throwable == null) { return false; } if (throwable.getMessage().contains(DO_NOT_LOG)) { return true; } final StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw)); return sw.toString().contains(DO_NOT_LOG); } protected void deactivate(final ComponentContext context) { logReaderService.removeLogListener(this); } public void logged(final LogEntry entry) { if (containsDoNotLogTag(entry.getException())) { // Only log Felix stack trace in development mode, discard log // otherwise if (isDevelopmentMode()) { logNow(entry, true); } } else { logNow(entry, false); } } private void logNow(final LogEntry entry, final boolean removeDoNotLogTag) { final int osgiLevel = entry.getLevel(); Level jdkLevel = Level.FINEST; // Convert the OSGi level into a JDK logger level if (osgiLevel == LogService.LOG_DEBUG) { jdkLevel = Level.FINE; } else if (osgiLevel == LogService.LOG_INFO) { jdkLevel = Level.INFO; } else if (osgiLevel == LogService.LOG_WARNING) { jdkLevel = Level.WARNING; } else if (osgiLevel == LogService.LOG_ERROR) { jdkLevel = Level.SEVERE; } if (jdkLevel.intValue() <= Level.INFO.intValue()) { // Not very important message, so just flash it if possible and // we're in development mode if (isDevelopmentMode()) { flash(jdkLevel, buildMessage(entry), MY_SLOT); // Immediately clear it once the timeout has been reached flash(jdkLevel, "", MY_SLOT); } } else { // Important log message, so log it via JDK if (removeDoNotLogTag) { LOGGER.log(jdkLevel, buildMessage(entry) + cleanThrowable(entry.getException())); } else { LOGGER.log(jdkLevel, buildMessage(entry), entry.getException()); } } } } |
blob | Naming, Long method, Duplicated code, Feature envy | t | f | f | Naming, Long method, Duplicated code, Feature envy | blob | 0 | 7719 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/runtime/felix/src/main/java/org/springframework/roo/felix/JdkDelegatingLogListener.java/#L37-L135 | 2 | 826 | 7719 | minor |
| 1656 | YES I found bad smells The bad smells are: Long method, Switch statement, Conditional logic, Dead code, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | Long method, Switch statement, Conditional logic, Dead code, Feature envy | t | f | f | Long method, Switch statement, Conditional logic, Dead code, Feature envy | blob | 0 | 11595 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 2 | 1656 | 11595 | minor |
| 2373 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14312 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 2 | 2373 | 14312 | minor |
| 1896 | YES I found bad smells 1. Long method, 2. Feature envy: the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | Long method, 2 Feature envy:the bad smells are: | t | f | f | . Long method, 2. Feature envy:the bad smells are: | data class | 0 | 12334 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 2 | 1896 | 12334 | major |
| 2434 | {"response":"YES I found bad smells","the bad smells are":["Blob","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 14462 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 2434 | 14462 | minor |
| 272 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class AffineMatrix implements ExtendedPrecisionMatrix, Serializable, Cloneable { /** * For cross-version compatibility. */ private static final long serialVersionUID = 1605578645060388327L; /** * The number of rows and columns of this matrix. */ private static final int SIZE = 3; /** * The length of an array containing all matrix elements. */ private static final int LENGTH = SIZE * SIZE; /** * The length of an array containing only the matrix elements to be stored. * The last row is omitted because it is assumed to contain (0 0 1). */ private static final int LENGTH_STORED = (SIZE - 1) * SIZE; /** * The length of an array containing all matrix elements together with error terms. */ private static final int LENGTH_EXTENDED = 2 * LENGTH; /** * The transform from which to get the matrix terms. */ private final AffineTransform transform; /** * The error terms, or {@code null} if none. * If non-null, then the length of this array shall be 6. */ private final double[] errors; /** * Creates a new matrix wrapping the given transform. * * @param transform the transform to wrap. * @param elements the elements used for creating the matrix (optionally with error terms), or {@code null}. */ AffineMatrix(final AffineTransform transform, final double[] elements) { this.transform = transform; if (elements != null) { assert elements.length == LENGTH || elements.length == LENGTH_EXTENDED; if (elements.length == LENGTH_EXTENDED) { errors = Arrays.copyOfRange(elements, LENGTH, LENGTH + LENGTH_STORED); /* * At this point we could check: * * assert Arrays.equals(elements, getExtendedElements()); * * but we do not, because the terms in the last row may not be exactly 0 or 1 * because of rounding errors. */ return; } } errors = null; } /** * Gets the number of rows in the matrix. */ @Override public int getNumRow() { return SIZE; } /** * Gets the number of columns in the matrix. */ @Override public int getNumCol() { return SIZE; } /** * Returns {@code true} if the backing affine transform is the identity transform. */ @Override public boolean isIdentity() { return transform.isIdentity(); } /** * Returns all matrix elements. */ @Override public double[] getExtendedElements() { final double[] elements = new double[errors != null ? LENGTH_EXTENDED : LENGTH]; if (errors != null) { System.arraycopy(errors, 0, elements, LENGTH, LENGTH_STORED); } elements[0] = transform.getScaleX(); elements[1] = transform.getShearX(); elements[2] = transform.getTranslateX(); elements[3] = transform.getShearY(); elements[4] = transform.getScaleY(); elements[5] = transform.getTranslateY(); elements[8] = 1; return elements; } /** * Returns the matrix element at the given index. */ @Override public final double getElement(final int row, final int column) { ArgumentChecks.ensureBetween("row", 0, SIZE, row); ArgumentChecks.ensureBetween("column", 0, SIZE, column); switch (row * SIZE + column) { case 0: return transform.getScaleX(); case 1: return transform.getShearX(); case 2: return transform.getTranslateX(); case 3: return transform.getShearY(); case 4: return transform.getScaleY(); case 5: return transform.getTranslateY(); case 6: // Fallthrough case 7: return 0; case 8: return 1; default: throw new AssertionError(); } } /** * Unsupported operation, since this matrix is unmodifiable. */ @Override public final void setElement(final int row, final int column, final double value) { throw new UnsupportedOperationException(Resources.format(Resources.Keys.UnmodifiableAffineTransform)); } /** * Returns a copy of the matrix that user can modify. */ @Override @SuppressWarnings("CloneDoesntCallSuperClone") public final Matrix clone() { return Matrices.copy(this); } /** * Compares this matrix with the given object for equality, including error terms (if any). */ @Override public boolean equals(final Object obj) { if (obj instanceof AffineMatrix) { final AffineMatrix other = (AffineMatrix) obj; return transform.equals(other.transform) && Arrays.equals(errors, other.errors); } return false; } /** * Returns a hash code value for this matrix. */ @Override public int hashCode() { return (transform.hashCode() * 31 + Arrays.hashCode(errors)) ^ (int) serialVersionUID; } /** * Returns a string representation of this matrix. * * @return a string representation of this matrix. */ @Override public String toString() { return Matrices.toString(this); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2924 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/j2d/AffineMatrix.java/#L38-L212 | 1 | 272 | 2924 | minor |
| 1844 | {"response": "YES I found bad smells", "bad_smells": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12159 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 2 | 1844 | 12159 | critical |
| 1794 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 11997 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 1794 | 11997 | minor |
| 2071 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | data class | t | t | f | data class | long method | 0 | 13025 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2071 | 13025 | major |
| 1921 | {"response": "YES I found bad smells the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
blob | 2. data class | t | t | f | 2. data class | blob | 0 | 12424 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 1921 | 12424 | minor |
| 2167 | { "answer": "YES, I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | blob | t | t | f | blob | data class | 0 | 13349 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 1 | 2167 | 13349 | major |
| 256 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2765 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 256 | 2765 | critical |
| 1553 | YES I found bad smells the bad smiles are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class DocumentsWriterDeleteQueue implements Accountable { // the current end (latest delete operation) in the delete queue: private volatile Node tail; /** Used to record deletes against all prior (already written to disk) segments. Whenever any segment flushes, we bundle up this set of * deletes and insert into the buffered updates stream before the newly flushed segment(s). */ private final DeleteSlice globalSlice; private final BufferedUpdates globalBufferedUpdates; // only acquired to update the global deletes, pkg-private for access by tests: final ReentrantLock globalBufferLock = new ReentrantLock(); final long generation; /** Generates the sequence number that IW returns to callers changing the index, showing the effective serialization of all operations. */ private final AtomicLong nextSeqNo; private final InfoStream infoStream; // for asserts long maxSeqNo = Long.MAX_VALUE; DocumentsWriterDeleteQueue(InfoStream infoStream) { // seqNo must start at 1 because some APIs negate this to also return a boolean this(infoStream, 0, 1); } DocumentsWriterDeleteQueue(InfoStream infoStream, long generation, long startSeqNo) { this(infoStream, new BufferedUpdates("global"), generation, startSeqNo); } DocumentsWriterDeleteQueue(InfoStream infoStream, BufferedUpdates globalBufferedUpdates, long generation, long startSeqNo) { this.infoStream = infoStream; this.globalBufferedUpdates = globalBufferedUpdates; this.generation = generation; this.nextSeqNo = new AtomicLong(startSeqNo); /* * we use a sentinel instance as our initial tail. No slice will ever try to * apply this tail since the head is always omitted. */ tail = new Node<>(null); // sentinel globalSlice = new DeleteSlice(tail); } long addDelete(Query... queries) { long seqNo = add(new QueryArrayNode(queries)); tryApplyGlobalSlice(); return seqNo; } long addDelete(Term... terms) { long seqNo = add(new TermArrayNode(terms)); tryApplyGlobalSlice(); return seqNo; } long addDocValuesUpdates(DocValuesUpdate... updates) { long seqNo = add(new DocValuesUpdatesNode(updates)); tryApplyGlobalSlice(); return seqNo; } static Node newNode(Term term) { return new TermNode(term); } static Node newNode(DocValuesUpdate... updates) { return new DocValuesUpdatesNode(updates); } /** * invariant for document update */ long add(Node deleteNode, DeleteSlice slice) { long seqNo = add(deleteNode); /* * this is an update request where the term is the updated documents * delTerm. in that case we need to guarantee that this insert is atomic * with regards to the given delete slice. This means if two threads try to * update the same document with in turn the same delTerm one of them must * win. By taking the node we have created for our del term as the new tail * it is guaranteed that if another thread adds the same right after us we * will apply this delete next time we update our slice and one of the two * competing updates wins! */ slice.sliceTail = deleteNode; assert slice.sliceHead != slice.sliceTail : "slice head and tail must differ after add"; tryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe // we can do it just every n times or so? return seqNo; } synchronized long add(Node newNode) { tail.next = newNode; this.tail = newNode; return getNextSequenceNumber(); } boolean anyChanges() { globalBufferLock.lock(); try { /* * check if all items in the global slice were applied * and if the global slice is up-to-date * and if globalBufferedUpdates has changes */ return globalBufferedUpdates.any() || !globalSlice.isEmpty() || globalSlice.sliceTail != tail || tail.next != null; } finally { globalBufferLock.unlock(); } } void tryApplyGlobalSlice() { if (globalBufferLock.tryLock()) { /* * The global buffer must be locked but we don't need to update them if * there is an update going on right now. It is sufficient to apply the * deletes that have been added after the current in-flight global slices * tail the next time we can get the lock! */ try { if (updateSliceNoSeqNo(globalSlice)) { globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } } finally { globalBufferLock.unlock(); } } } FrozenBufferedUpdates freezeGlobalBuffer(DeleteSlice callerSlice) throws IOException { globalBufferLock.lock(); /* * Here we freeze the global buffer so we need to lock it, apply all * deletes in the queue and reset the global slice to let the GC prune the * queue. */ final Node currentTail = tail; // take the current tail make this local any // Changes after this call are applied later // and not relevant here if (callerSlice != null) { // Update the callers slices so we are on the same page callerSlice.sliceTail = currentTail; } try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } if (globalBufferedUpdates.any()) { final FrozenBufferedUpdates packet = new FrozenBufferedUpdates(infoStream, globalBufferedUpdates, null); globalBufferedUpdates.clear(); return packet; } else { return null; } } finally { globalBufferLock.unlock(); } } DeleteSlice newSlice() { return new DeleteSlice(tail); } /** Negative result means there were new deletes since we last applied */ synchronized long updateSlice(DeleteSlice slice) { long seqNo = getNextSequenceNumber(); if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; seqNo = -seqNo; } return seqNo; } /** Just like updateSlice, but does not assign a sequence number */ boolean updateSliceNoSeqNo(DeleteSlice slice) { if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; return true; } return false; } static class DeleteSlice { // No need to be volatile, slices are thread captive (only accessed by one thread)! Node sliceHead; // we don't apply this one Node sliceTail; DeleteSlice(Node currentTail) { assert currentTail != null; /* * Initially this is a 0 length slice pointing to the 'current' tail of * the queue. Once we update the slice we only need to assign the tail and * have a new slice */ sliceHead = sliceTail = currentTail; } void apply(BufferedUpdates del, int docIDUpto) { if (sliceHead == sliceTail) { // 0 length slice return; } /* * When we apply a slice we take the head and get its next as our first * item to apply and continue until we applied the tail. If the head and * tail in this slice are not equal then there will be at least one more * non-null node in the slice! */ Node current = sliceHead; do { current = current.next; assert current != null : "slice property violated between the head on the tail must not be a null node"; current.apply(del, docIDUpto); } while (current != sliceTail); reset(); } void reset() { // Reset to a 0 length slice sliceHead = sliceTail; } /** * Returns true iff the given node is identical to the the slices tail, * otherwise false. */ boolean isTail(Node node) { return sliceTail == node; } /** * Returns true iff the given item is identical to the item * hold by the slices tail, otherwise false. */ boolean isTailItem(Object object) { return sliceTail.item == object; } boolean isEmpty() { return sliceHead == sliceTail; } } public int numGlobalTermDeletes() { return globalBufferedUpdates.numTermDeletes.get(); } void clear() { globalBufferLock.lock(); try { final Node currentTail = tail; globalSlice.sliceHead = globalSlice.sliceTail = currentTail; globalBufferedUpdates.clear(); } finally { globalBufferLock.unlock(); } } static class Node { volatile Node next; final T item; Node(T item) { this.item = item; } void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { throw new IllegalStateException("sentinel item must never be applied"); } boolean isDelete() { return true; } } private static final class TermNode extends Node { TermNode(Term term) { super(term); } @Override void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { bufferedDeletes.addTerm(item, docIDUpto); } @Override public String toString() { return "del=" + item; } } private static final class QueryArrayNode extends Node { QueryArrayNode(Query[] query) { super(query); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Query query : item) { bufferedUpdates.addQuery(query, docIDUpto); } } } private static final class TermArrayNode extends Node { TermArrayNode(Term[] term) { super(term); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Term term : item) { bufferedUpdates.addTerm(term, docIDUpto); } } @Override public String toString() { return "dels=" + Arrays.toString(item); } } private static final class DocValuesUpdatesNode extends Node { DocValuesUpdatesNode(DocValuesUpdate... updates) { super(updates); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (DocValuesUpdate update : item) { switch (update.type) { case NUMERIC: bufferedUpdates.addNumericUpdate((NumericDocValuesUpdate) update, docIDUpto); break; case BINARY: bufferedUpdates.addBinaryUpdate((BinaryDocValuesUpdate) update, docIDUpto); break; default: throw new IllegalArgumentException(update.type + " DocValues updates not supported yet!"); } } } @Override boolean isDelete() { return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("docValuesUpdates: "); if (item.length > 0) { sb.append("term=").append(item[0].term).append("; updates: ["); for (DocValuesUpdate update : item) { sb.append(update.field).append(':').append(update.valueToString()).append(','); } sb.setCharAt(sb.length()-1, ']'); } return sb.toString(); } } private boolean forceApplyGlobalSlice() { globalBufferLock.lock(); final Node currentTail = tail; try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } return globalBufferedUpdates.any(); } finally { globalBufferLock.unlock(); } } public int getBufferedUpdatesTermsSize() { globalBufferLock.lock(); try { forceApplyGlobalSlice(); return globalBufferedUpdates.deleteTerms.size(); } finally { globalBufferLock.unlock(); } } @Override public long ramBytesUsed() { return globalBufferedUpdates.ramBytesUsed(); } @Override public String toString() { return "DWDQ: [ generation: " + generation + " ]"; } public long getNextSequenceNumber() { long seqNo = nextSeqNo.getAndIncrement(); assert seqNo < maxSeqNo: "seqNo=" + seqNo + " vs maxSeqNo=" + maxSeqNo; return seqNo; } public long getLastSequenceNumber() { return nextSeqNo.get()-1; } /** Inserts a gap in the sequence numbers. This is used by IW during flush or commit to ensure any in-flight threads get sequence numbers * inside the gap */ public void skipSequenceNumbers(long jump) { nextSeqNo.addAndGet(jump); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11272 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java/#L71-L495 | 2 | 1553 | 11272 | major |
| 839 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 7778 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 839 | 7778 | minor |
| 1551 | NO, I did not find any bad smell in the given code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11265 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 1551 | 11265 | minor | ||
| 1181 | { "NO, I did not find any bad smell" : "the bad smells are:" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | "the bad smells are | f | f | f | "the bad smells are | data class | 0 | 10234 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 1181 | 10234 | critical |
| 2229 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | long method | t | t | f | long method | blob | 0 | 13583 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 2229 | 13583 | minor |
| 129 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StringFunctions { /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function appendOld(final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function prependOld(final String prefix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterForArrayOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function, String> joinerOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function, String>() { public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function joinerForArrayOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function lengthOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function surroundOld(final String prefix, final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function trimOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toLowerCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toLowerCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toUpperCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toUpperCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function convertCaseOld(final CaseFormat src, final CaseFormat target) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return src.to(target, input); } }; } public static Function append(final String suffix) { return new AppendFunction(checkNotNull(suffix, "suffix")); } private static class AppendFunction implements Function { private final String suffix; public AppendFunction(String suffix) { this.suffix = suffix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; public static Function prepend(final String prefix) { return new PrependFunction(checkNotNull(prefix, "prefix")); } protected static class PrependFunction implements Function { private final String prefix; public PrependFunction(String prefix) { this.prefix = prefix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } } /** given e.g. "hello %s" returns a function which will insert a string into that pattern */ public static Function formatter(final String pattern) { return new FormatterFunction(pattern); } protected static class FormatterFunction implements Function { private final String pattern; FormatterFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object input) { return String.format(pattern, input); } }; /** given e.g. "hello %s %s" returns a function which will insert an array of two strings into that pattern */ public static Function formatterForArray(final String pattern) { return new FormatterForArrayFunction(checkNotNull(pattern, "pattern")); } protected static class FormatterForArrayFunction implements Function { private final String pattern; public FormatterForArrayFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object[] input) { return String.format(pattern, input); } } /** * Given e.g. "hello %s %s" returns a function which will insert an Iterable of two strings into that pattern * * @since 0.9.0 */ public static Function, String> formatterForIterable(final String pattern) { return new FormatterForIterableFunction(pattern); } protected static class FormatterForIterableFunction implements Function, String> { final String pattern; public FormatterForIterableFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Iterable input) { Object[] arr = (input == null) ? null : Iterables.toArray(input, Object.class); return String.format(pattern, arr); } } /** joins the given objects in a collection as a toString with the given separator */ public static Function, String> joiner(final String separator) { return new JoinerFunction(separator); } private static class JoinerFunction implements Function, String> { private final String separator; public JoinerFunction(String separator) { this.separator = separator; } public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } } /** joins the given objects as a toString with the given separator, but expecting an array of objects, not a collection */ public static Function joinerForArray(final String separator) { return new JoinerForArrayFunction(checkNotNull(separator, "separator")); } private static class JoinerForArrayFunction implements Function { private final String separator; protected JoinerForArrayFunction(String separator) { this.separator = separator; } public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } } /** provided here as a convenience; prefer {@link Functions#toStringFunction()} */ public static Function toStringFunction() { return Functions.toStringFunction(); } /** returns function which gives length of input, with -1 for nulls */ public static Function length() { return new LengthFunction(); } protected static class LengthFunction implements Function { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } } /** Surrounds an input string with the given prefix and suffix */ public static Function surround(final String prefix, final String suffix) { Preconditions.checkNotNull(prefix); Preconditions.checkNotNull(suffix); return new SurroundFunction(prefix, suffix); } protected static class SurroundFunction implements Function { private final String prefix; private final String suffix; public SurroundFunction(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } } public static Function trim() { return new TrimFunction(); } protected static class TrimFunction implements Function { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } } public static Function toLowerCase() { return new LowerCaseFunction(); } protected static class LowerCaseFunction implements Function { @Override public String apply(String input) { return input.toLowerCase(); } } public static Function toUpperCase() { return new UpperCaseFunction(); } protected static class UpperCaseFunction implements Function { @Override public String apply(String input) { return input.toUpperCase(); } } public static Function convertCase(final CaseFormat src, final CaseFormat target) { return new ConvertCaseFunction(checkNotNull(src, "src"), checkNotNull(target, "target")); } protected static class ConvertCaseFunction implements Function { private final CaseFormat src; private final CaseFormat target; public ConvertCaseFunction(CaseFormat src, CaseFormat target) { this.src = src; this.target = target; } @Override public String apply(String input) { return src.to(target, input); } } public static class RegexReplacer implements Function { private final String pattern; private final String replacement; public RegexReplacer(String pattern, String replacement) { this.pattern = pattern; this.replacement = replacement; } @Nullable @Override public String apply(@Nullable String s) { return Strings.replaceAllRegex(s, pattern, replacement); } } } |
blob | long method | t | t | f | long method | blob | 0 | 1607 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java/#L32-L415 | 1 | 129 | 1607 | major |
| 2066 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12994 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 2 | 2066 | 12994 | minor |
| 1969 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12606 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1969 | 12606 | major |
| 47 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 840 | https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 | 1 | 47 | 840 | minor |
| 640 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6350 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 1 | 640 | 6350 | major |
| 2460 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method | t | t | f | long method | data class | 0 | 14540 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 2460 | 14540 | major |
| 532 | {"answer": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 5478 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 1 | 532 | 5478 | minor |
| 1159 | { "answer": "YES, I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 10159 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 1 | 1159 | 10159 | minor |
| 187 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method | t | t | f | long method | data class | 0 | 2120 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 187 | 2120 | major |
| 1517 | {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11166 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 1 | 1517 | 11166 | minor |
| 4078 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @HaHotStateRequired public class SensorResource extends AbstractBrooklynRestResource implements SensorApi { private static final Logger log = LoggerFactory.getLogger(SensorResource.class); @Override public List list(final String application, final String entityToken) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } List result = Lists.newArrayList(); for (AttributeSensor sensor : filter(entity.getEntityType().getSensors(), AttributeSensor.class)) { // Exclude config that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from AttributeSensor list results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } result.add(SensorTransformer.sensorSummary(entity, sensor, ui.getBaseUriBuilder())); } return result; } @Override public Map batchSensorRead(final String application, final String entityToken, final Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } Map sensorMap = Maps.newHashMap(); @SuppressWarnings("rawtypes") Iterable sensors = filter(entity.getEntityType().getSensors(), AttributeSensor.class); for (AttributeSensor sensor : sensors) { // Exclude sensors that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from current-state results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } Object value = entity.getAttribute(findSensor(entity, sensor.getName())); sensorMap.put(sensor.getName(), resolving(value).preferJson(true).asJerseyOutermostReturnValue(false).raw(raw).context(entity).timeout(Duration.ZERO).renderAs(sensor).resolve()); } return sensorMap; } protected Object get(boolean preferJson, String application, String entityToken, String sensorName, Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); AttributeSensor sensor = findSensor(entity, sensorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s' sensor '%s'", Entitlements.getEntitlementContext().user(), entity, sensor.getName()); } Object value = entity.getAttribute(sensor); return resolving(value).preferJson(preferJson).asJerseyOutermostReturnValue(true).raw(raw).context(entity).immediately(true).renderAs(sensor).resolve(); } @Override public String getPlain(String application, String entityToken, String sensorName, final Boolean raw) { return (String) get(false, application, entityToken, sensorName, raw); } @Override public Object get(final String application, final String entityToken, String sensorName, final Boolean raw) { return get(true, application, entityToken, sensorName, raw); } private AttributeSensor findSensor(Entity entity, String name) { Sensor s = entity.getEntityType().getSensor(name); if (s instanceof AttributeSensor) return (AttributeSensor) s; return new BasicAttributeSensor(Object.class, name); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void setFromMap(String application, String entityToken, Map newValues) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensors "+newValues); for (Object entry: newValues.entrySet()) { String sensorName = Strings.toString(((Map.Entry)entry).getKey()); Object newValue = ((Map.Entry)entry).getValue(); AttributeSensor sensor = findSensor(entity, sensorName); entity.sensors().set(sensor, newValue); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void set(String application, String entityToken, String sensorName, Object newValue) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensor "+sensorName+" to "+newValue); entity.sensors().set(sensor, newValue); } @Override public void delete(String application, String entityToken, String sensorName) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" deleting sensor "+sensorName); ((EntityInternal)entity).sensors().remove(sensor); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 10755 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/SensorResource.java/#L46-L183 | 2 | 4078 | 10755 | major |
| 63 | {"response": "YES I found bad smells", "bad smells are": "1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1067 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 63 | 1067 | major |
| 1686 | YES I found bad smells 1. Feature envy 2. Long method 3. Primitive obsession 4. Feature envy 5. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
blob | Feature envy2 Long method3 Primitive obsession4 Feature envy5 Lazy class | t | f | f | . Feature envy2. Long method3. Primitive obsession4. Feature envy5. Lazy class | blob | 0 | 11687 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 1686 | 11687 | minor |
| 5395 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 15164 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 5395 | 15164 | minor | ||
| 146 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1826 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 2 | 146 | 1826 | minor |
| 518 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | long method | t | t | f | long method | blob | 0 | 5378 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 1 | 518 | 5378 | minor |
| 53 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout) throws IOException { final ProxyParams proxyParams = prepareProxyParams(); return executeUrl(httpMethod, url, httpHeaders, content, contentType, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 879 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/io/org.eclipse.smarthome.io.net/src/main/java/org/eclipse/smarthome/io/net/http/HttpUtil.java/#L127-L133 | 1 | 53 | 879 | major |
| 2693 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | long method | t | t | f | long method | blob | 0 | 15309 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 2693 | 15309 | minor |
| 849 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class SearchFirstStringNode extends Node { private static final int[] UNINTIALIZED_CACHED_INDICES = new int[0]; private final VectorLengthProfile targetLengthProfile = VectorLengthProfile.create(); private final VectorLengthProfile elementsLengthProfile = VectorLengthProfile.create(); private final ValueProfile targetClassProfile = ValueProfile.createClassProfile(); private final ValueProfile elementsClassProfile = ValueProfile.createClassProfile(); @Child private StringEqualsNode stringEquals = CompareStringNode.createEquals(); @Child private CompareStringNode stringStartsWith; @Child private StringEqualsNode equalsDuplicate; private final NACheck elementsNACheck = NACheck.create(); private final NACheck targetNACheck = NACheck.create(); private final BranchProfile everFoundDuplicate = BranchProfile.create(); private final BranchProfile seenInvalid = BranchProfile.create(); /** Instead of using the notFoundStartIndex we use NA. */ private final boolean useNAForNotFound; private final boolean exactMatch; @CompilationFinal(dimensions = 1) private int[] cachedIndices; private SearchFirstStringNode(boolean exactMatch, boolean useNAForNotFound) { this.exactMatch = exactMatch; this.useNAForNotFound = useNAForNotFound; if (!exactMatch) { stringStartsWith = CompareStringNode.createStartsWith(); } } public RAbstractIntVector apply(RAbstractStringVector target, RAbstractStringVector elements, int notFoundStartIndex, RStringVector names) { RAbstractStringVector targetProfiled = targetClassProfile.profile(target); RAbstractStringVector elementsProfiled = elementsClassProfile.profile(elements); int targetLength = targetLengthProfile.profile(targetProfiled.getLength()); int elementsLength = elementsLengthProfile.profile(elementsProfiled.getLength()); targetNACheck.enable(target); elementsNACheck.enable(elements); if (cachedIndices == UNINTIALIZED_CACHED_INDICES) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = searchCached(targetProfiled, targetLength, elementsProfiled, elementsLength, names); } if (cachedIndices != null) { if (!isCacheValid(targetProfiled, targetLength, elementsProfiled, elementsLength, cachedIndices)) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = null; // set to generic // fallthrough to generic } else { assert sameVector(searchCached(target, targetLength, elements, elementsLength, names), cachedIndices); return RDataFactory.createIntVector(cachedIndices, true, names); } } return searchGeneric(targetProfiled, targetLength, elementsProfiled, elementsLength, notFoundStartIndex, false, names); } public static SearchFirstStringNode createNode(boolean exactMatch, boolean useNAForNotFound) { return new SearchFirstStringNode(exactMatch, useNAForNotFound); } private int[] searchCached(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, RStringVector names) { if (exactMatch) { RAbstractIntVector genericResult = searchGeneric(target, targetLength, elements, elementsLength, -1, true, names); if (genericResult != null) { return genericResult.materialize().getReadonlyData(); } } return null; } private boolean isCacheValid(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int[] cached) { int cachedLength = cached.length; if (elementsLength != cachedLength) { seenInvalid.enter(); return false; } for (int i = 0; i < cachedLength; i++) { int cachedIndex = cached[i]; String cachedElement = elements.getDataAt(i); int cachedElementHash = cachedElement.hashCode(); assert !elementsNACheck.check(cachedElement) && cachedElement.length() > 0; int cachedTranslatedIndex = cachedIndex - 1; for (int j = 0; j < cachedTranslatedIndex; j++) { String targetString = target.getDataAt(j); if (!targetNACheck.check(targetString) && stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } if (cachedTranslatedIndex < targetLength) { String targetString = target.getDataAt(cachedTranslatedIndex); if (!targetNACheck.check(targetString) && !stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } else { seenInvalid.enter(); return false; } } return true; } private static boolean sameVector(int[] a, int[] b) { if (a == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } private final BranchProfile notFoundProfile = BranchProfile.create(); private final ConditionProfile hashingProfile = ConditionProfile.createBinaryProfile(); private RAbstractIntVector searchGeneric(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int notFoundStartIndex, boolean nullOnNotFound, RStringVector names) { int[] indices = new int[elementsLength]; boolean resultComplete = true; long hashingCost = targetLength * 10L + 10 /* constant overhead */; long lookupCost = elementsLength * 2L; long nestedLoopCost = targetLength * (long) elementsLength; NonRecursiveHashMapCharacter map; if (hashingProfile.profile(nestedLoopCost > hashingCost + lookupCost)) { map = new NonRecursiveHashMapCharacter(targetLength); for (int i = 0; i < targetLength; i++) { String name = target.getDataAt(i); if (!targetNACheck.check(name)) { map.put(name, i); } } } else { map = null; } int notFoundIndex = notFoundStartIndex; for (int i = 0; i < elementsLength; i++) { String element = elements.getDataAt(i); boolean isElementNA = elementsNACheck.check(element) || element.length() == 0; if (!isElementNA) { int index; if (map != null) { index = map.get(element); if (!exactMatch && index < 0) { // the map is only good for exact matches index = findNonExactIndex(target, targetLength, element); } } else { index = findIndex(target, targetLength, element); } if (index >= 0) { indices[i] = index + 1; continue; } } notFoundProfile.enter(); if (nullOnNotFound) { return null; } else { int prevDuplicateIndex = -1; if (!isElementNA) { prevDuplicateIndex = findFirstDuplicate(elements, element, i); } int nextIndex; if (prevDuplicateIndex == -1) { if (useNAForNotFound) { resultComplete = false; nextIndex = RRuntime.INT_NA; } else { nextIndex = ++notFoundIndex; } } else { nextIndex = indices[prevDuplicateIndex]; } indices[i] = nextIndex; } } return RDataFactory.createIntVector(indices, resultComplete && elements.isComplete(), names); } private int findNonExactIndex(RAbstractStringVector target, int targetLength, String element) { assert !exactMatch; int nonExactIndex = -1; for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { return -1; } } } } return nonExactIndex; } private int findIndex(RAbstractStringVector target, int targetLength, String element) { int nonExactIndex = -1; int elementHash = element.hashCode(); for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringEquals.executeCompare(element, elementHash, targetValue)) { return j; } if (!exactMatch) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { nonExactIndex = -2; } } } } } return nonExactIndex; } private int findFirstDuplicate(RAbstractStringVector elements, String element, int currentIndex) { if (equalsDuplicate == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); equalsDuplicate = insert(CompareStringNode.createEquals()); } int elementHash = element.hashCode(); for (int j = 0; j < currentIndex; j++) { String otherElement = elements.getDataAt(j); if (!targetNACheck.check(otherElement) && equalsDuplicate.executeCompare(element, elementHash, otherElement)) { everFoundDuplicate.enter(); return j; } } return -1; } abstract static class CompareStringNode extends Node { public abstract boolean executeCompare(String a, String b); public static StringEqualsNode createEquals() { return new StringEqualsNode(); } public static StringStartsWithNode createStartsWith() { return new StringStartsWithNode(); } public static class StringEqualsNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); private final ConditionProfile hashEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(a.hashCode() != b.hashCode())) { return false; } return a.equals(b); } } public final boolean executeCompare(String a, int aHash, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(aHash != b.hashCode())) { return false; } return a.equals(b); } } } private static class StringStartsWithNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { return a.startsWith(b); } } } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 7848 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/SearchFirstStringNode.java/#L46-L361 | 1 | 849 | 7848 | major |
| 665 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | long method | t | t | f | long method | blob | 0 | 6531 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 1 | 665 | 6531 | minor |
| 5782 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 15318 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5782 | 15318 | minor |
| 2634 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15114 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2634 | 15114 | minor |
| 2009 | { "input_code": "public class Customer {\n private String name;\n private int age;\n \n public Customer(String name, int age) {\n this.name = name;\n this.age = age;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public int getAge() {\n return age;\n }\n \n public void setAge(int age) {\n this.age = age;\n }\n}\n", "code_smells_to_check": ["Blob", "Data Class", "Feature Envy", "Long Method"], "detected_code_smells": [] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | t | t | f | blob | 0 | 12742 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/protocol/src/main/java/org/apache/drill/exec/proto/UserProtos.java/#L19445-L20118 | 1 | 2009 | 12742 | critical | ||
| 818 | {"message":"YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 7672 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 2 | 818 | 7672 | critical |
| 2594 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15004 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 2594 | 15004 | critical |
| 2622 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 15059 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 2622 | 15059 | critical |
| 1655 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11587 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 1655 | 11587 | minor |
| 1625 | YES I found bad smells 1. Long method 2. Long parameter list 3. Feature envy 4. Indecent exposure 5. Speculative generality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Long parameter list3 Feature envy4 Indecent exposure5 Speculative generality | t | f | f | . Long method2. Long parameter list3. Feature envy4. Indecent exposure5. Speculative generality | data class | 0 | 11499 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 1625 | 11499 | major |
| 541 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers (42) 4. Useless constructor injection (the 'id' variable is not used in the constructor) 5. Useless annotations (@Accessors and @Pure) 6. Useless method naming (testFunction1, testFunction2, testFunction3) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Long method2 Feature envy3 Magic numbers (42)4 Useless constructor injection (the 'id' variable is not used in the constructor)5 Useless annotations (@Accessors and @Pure)6 Useless method naming (testFunction | t | f | f | . Long method2. Feature envy3. Magic numbers (42)4. Useless constructor injection (the 'id' variable is not used in the constructor)5. Useless annotations (@Accessors and @Pure)6. Useless method naming (testFunction | data class | 0 | 5537 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 541 | 5537 | major |
| 1202 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
blob | Feature envy | t | f | f | . Feature envy | blob | 0 | 10285 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 2 | 1202 | 10285 | major |
| 25 | {"response": "YES, I found bad smells. The bad smells are: 1.Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Key)) { return false; } Key key = (Key) o; return annotationType.equals(key.annotationType) && type.equals(key.type); } |
feature envy | 1.long method | t | t | f | 1.long method | feature envy | 0 | 693 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/commons/che-core-commons-inject/src/main/java/org/eclipse/che/inject/lifecycle/LifecycleModule.java/#L40-L50 | 2 | 25 | 693 | minor |
| 1129 | {"response": "YES I found bad smells - the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean hasCmpPersistenceUnit(final Persistence persistence) { for (final PersistenceUnit unit : persistence.getPersistenceUnit()) { if (unit.getName().startsWith("cmp")) { return true; } } return false; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10016 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/config/OutputGeneratedDescriptors.java/#L173-L180 | 1 | 1129 | 10016 | minor |
| 3587 | { "message": "Please provide the Java code for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 7921 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 3587 | 7921 | minor | |
| 1868 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12244 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 1868 | 12244 | critical |
| 771 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 7278 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 771 | 7278 | minor |
| 826 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component @Reference(name = "shell", strategy = ReferenceStrategy.EVENT, policy = ReferencePolicy.DYNAMIC, referenceInterface = Shell.class, cardinality = ReferenceCardinality.OPTIONAL_UNARY) public class JdkDelegatingLogListener extends AbstractFlashingObject implements LogListener { public static final String DO_NOT_LOG = "#DO_NOT_LOG"; private final static Logger LOGGER = HandlerUtils.getLogger(JdkDelegatingLogListener.class); @Reference(policy = ReferencePolicy.DYNAMIC) private volatile LogReaderService logReaderService; public static String cleanThrowable(final Throwable throwable) { final StringBuilder result = new StringBuilder(); result.append(LINE_SEPARATOR); result.append(throwable.toString().replace(DO_NOT_LOG, "")); result.append(LINE_SEPARATOR); for (final StackTraceElement ste : throwable.getStackTrace()) { result.append(ste); result.append(LINE_SEPARATOR); } return result.toString(); } @SuppressWarnings("unchecked") protected void activate(final ComponentContext context) { logReaderService.addLogListener(this); final Enumeration latestLogs = logReaderService.getLog(); if (latestLogs.hasMoreElements()) { logNow(latestLogs.nextElement(), false); } } private String buildMessage(final LogEntry entry) { final StringBuilder sb = new StringBuilder(); sb.append("[").append(entry.getBundle()).append("] ").append(entry.getMessage()); return sb.toString(); } private boolean containsDoNotLogTag(final Throwable throwable) { if (throwable == null) { return false; } if (throwable.getMessage().contains(DO_NOT_LOG)) { return true; } final StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw)); return sw.toString().contains(DO_NOT_LOG); } protected void deactivate(final ComponentContext context) { logReaderService.removeLogListener(this); } public void logged(final LogEntry entry) { if (containsDoNotLogTag(entry.getException())) { // Only log Felix stack trace in development mode, discard log // otherwise if (isDevelopmentMode()) { logNow(entry, true); } } else { logNow(entry, false); } } private void logNow(final LogEntry entry, final boolean removeDoNotLogTag) { final int osgiLevel = entry.getLevel(); Level jdkLevel = Level.FINEST; // Convert the OSGi level into a JDK logger level if (osgiLevel == LogService.LOG_DEBUG) { jdkLevel = Level.FINE; } else if (osgiLevel == LogService.LOG_INFO) { jdkLevel = Level.INFO; } else if (osgiLevel == LogService.LOG_WARNING) { jdkLevel = Level.WARNING; } else if (osgiLevel == LogService.LOG_ERROR) { jdkLevel = Level.SEVERE; } if (jdkLevel.intValue() <= Level.INFO.intValue()) { // Not very important message, so just flash it if possible and // we're in development mode if (isDevelopmentMode()) { flash(jdkLevel, buildMessage(entry), MY_SLOT); // Immediately clear it once the timeout has been reached flash(jdkLevel, "", MY_SLOT); } } else { // Important log message, so log it via JDK if (removeDoNotLogTag) { LOGGER.log(jdkLevel, buildMessage(entry) + cleanThrowable(entry.getException())); } else { LOGGER.log(jdkLevel, buildMessage(entry), entry.getException()); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7719 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/runtime/felix/src/main/java/org/springframework/roo/felix/JdkDelegatingLogListener.java/#L37-L135 | 1 | 826 | 7719 | minor |
| 918 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8254 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 1 | 918 | 8254 | major |
| 1952 | {"response": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | long method | t | t | f | long method | blob | 0 | 12536 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 1 | 1952 | 12536 | major |
| 3236 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 5427 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 2 | 3236 | 5427 | critical |
| 2128 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13224 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 2128 | 13224 | major |
| 1812 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12063 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 1812 | 12063 | minor |
| 2706 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15347 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 2706 | 15347 | major |
| 1952 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12536 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 2 | 1952 | 12536 | major |
| 1062 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 9545 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 2 | 1062 | 9545 | minor |
| 4527 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12002 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L241837-L241908 | 2 | 4527 | 12002 | minor | ||
| 2679 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 15254 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2679 | 15254 | minor |
| 12 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 619 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 12 | 619 | major |
| 2417 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14422 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 2 | 2417 | 14422 | major |
| 852 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CConstantValueSupportImpl implements CConstantValueSupport { private final NativeLibraries nativeLibraries; private final MetaAccessProvider metaAccess; public CConstantValueSupportImpl(NativeLibraries nativeLibraries, MetaAccessProvider metaAccess) { this.nativeLibraries = nativeLibraries; this.metaAccess = metaAccess; } @Override public T getCConstantValue(Class declaringClass, String methodName, Class returnType) { ResolvedJavaMethod method; try { method = metaAccess.lookupJavaMethod(declaringClass.getMethod(methodName)); } catch (NoSuchMethodException | SecurityException e) { throw VMError.shouldNotReachHere("Method not found: " + declaringClass.getName() + "." + methodName); } if (method.getAnnotation(CConstant.class) == null) { throw VMError.shouldNotReachHere("Method " + declaringClass.getName() + "." + methodName + " is not annotated with @" + CConstant.class.getSimpleName()); } ConstantInfo constantInfo = (ConstantInfo) nativeLibraries.findElementInfo(method); Object value = constantInfo.getValueInfo().getProperty(); switch (constantInfo.getKind()) { case INTEGER: case POINTER: Long longValue = (Long) value; if (returnType == Boolean.class) { return returnType.cast(Boolean.valueOf(longValue.longValue() != 0)); } else if (returnType == Integer.class) { return returnType.cast(Integer.valueOf((int) longValue.longValue())); } else if (returnType == Long.class) { return returnType.cast(value); } break; case FLOAT: if (returnType == Double.class) { return returnType.cast(value); } break; case STRING: if (returnType == String.class) { return returnType.cast(value); } break; case BYTEARRAY: if (returnType == byte[].class) { return returnType.cast(value); } break; } throw VMError.shouldNotReachHere("Unexpected returnType: " + returnType.getName()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7853 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/c/CConstantValueSupportImpl.java/#L36-L93 | 2 | 852 | 7853 | minor |
| 685 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6616 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 2 | 685 | 6616 | minor |
| 198 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 2238 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 198 | 2238 | major |
| 190 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 2196 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 190 | 2196 | major |
| 2677 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | long method | t | t | f | long method | blob | 0 | 15243 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 1 | 2677 | 15243 | minor |
| 2194 | {"message": "YES I found bad smells", "the bad smells are": "1. Long Method, 2. Feature Envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 13479 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 2 | 2194 | 13479 | minor |
| 131 | { "response": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static long gzip(final ByteSource in, final ByteSink out, Predicate shouldRetry) { return StreamUtils.retryCopy( in, new ByteSink() { @Override public OutputStream openStream() throws IOException { return new GZIPOutputStream(out.openStream()); } }, shouldRetry, DEFAULT_RETRY_COUNT ); } |
feature envy | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | feature envy | 0 | 1618 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/utils/CompressionUtils.java/#L491-L506 | 1 | 131 | 1618 | minor |
| 1025 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9360 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1025 | 9360 | major |
| 2233 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13595 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 2 | 2233 | 13595 | minor |
| 5182 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | "NO, I did not find any bad smell"} | f | f | f | "NO, I did not find any bad smell"} | long method | 0 | 14493 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xtext.ui.examples/projects/domainmodel/org.eclipse.xtext.example.domainmodel.ide/src-gen/org/eclipse/xtext/example/domainmodel/ide/contentassist/antlr/internal/InternalDomainmodelParser.java/#L62002-L62027 | 1 | 5182 | 14493 | minor |
| 228 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2451 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 2 | 228 | 2451 | minor |
| 4543 | {"result": "YES I found bad smells", "bad smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
blob | feature envy | t | t | f | feature envy | blob | 0 | 12066 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 4543 | 12066 | minor |
| 582 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5787 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 582 | 5787 | major |
| 1131 | { "output": "YES I found bad smells the bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class SwiftUtils { public static final String READ = "read(buffer, offset, length)"; /** * Join two (non null) paths, inserting a forward slash between them * if needed * * @param path1 first path * @param path2 second path * @return the combined path */ public static String joinPaths(String path1, String path2) { StringBuilder result = new StringBuilder(path1.length() + path2.length() + 1); result.append(path1); boolean insertSlash = true; if (path1.endsWith("/")) { insertSlash = false; } else if (path2.startsWith("/")) { insertSlash = false; } if (insertSlash) { result.append("/"); } result.append(path2); return result.toString(); } /** * This test contains the is-directory logic for Swift, so if * changed there is only one place for it. * * @param fileStatus status to examine * @return true if we consider this status to be representative of a * directory. */ public static boolean isDirectory(FileStatus fileStatus) { return fileStatus.isDirectory() || isFilePretendingToBeDirectory(fileStatus); } /** * Test for the entry being a file that is treated as if it is a * directory * * @param fileStatus status * @return true if it meets the rules for being a directory */ public static boolean isFilePretendingToBeDirectory(FileStatus fileStatus) { return fileStatus.getLen() == 0; } /** * Predicate: Is a swift object referring to the root directory? * @param swiftObject object to probe * @return true iff the object refers to the root */ public static boolean isRootDir(SwiftObjectPath swiftObject) { return swiftObject.objectMatches("") || swiftObject.objectMatches("/"); } /** * Sprintf() to the log iff the log is at debug level. If the log * is not at debug level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void debug(Logger log, String text, Object... args) { if (log.isDebugEnabled()) { log.debug(String.format(text, args)); } } /** * Log an exception (in text and trace) iff the log is at debug * @param log Log to use * @param text text message * @param ex exception */ public static void debugEx(Logger log, String text, Exception ex) { if (log.isDebugEnabled()) { log.debug(text + ex, ex); } } /** * Sprintf() to the log iff the log is at trace level. If the log * is not at trace level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void trace(Logger log, String text, Object... args) { if (log.isTraceEnabled()) { log.trace(String.format(text, args)); } } /** * Given a partition number, calculate the partition value. * This is used in the SwiftNativeOutputStream, and is placed * here for tests to be able to calculate the filename of * a partition. * @param partNumber part number * @return a string to use as the filename */ public static String partitionFilenameFromNumber(int partNumber) { return String.format("%06d", partNumber); } /** * List a a path to string * @param fileSystem filesystem * @param path directory * @return a listing of the filestatuses of elements in the directory, one * to a line, preceded by the full path of the directory * @throws IOException connectivity problems */ public static String ls(FileSystem fileSystem, Path path) throws IOException { if (path == null) { //surfaces when someone calls getParent() on something at the top of the path return "/"; } FileStatus[] stats; String pathtext = "ls " + path; try { stats = fileSystem.listStatus(path); } catch (FileNotFoundException e) { return pathtext + " -file not found"; } catch (IOException e) { return pathtext + " -failed: " + e; } return pathtext + fileStatsToString(stats, "\n"); } /** * Take an array of filestatus and convert to a string (prefixed w/ a [01] counter * @param stats array of stats * @param separator separator after every entry * @return a stringified set */ public static String fileStatsToString(FileStatus[] stats, String separator) { StringBuilder buf = new StringBuilder(stats.length * 128); for (int i = 0; i < stats.length; i++) { buf.append(String.format("[%02d] %s", i, stats[i])).append(separator); } return buf.toString(); } /** * Verify that the basic args to a read operation are valid; * throws an exception if not -with meaningful text including * @param buffer destination buffer * @param off offset * @param len number of bytes to read * @throws NullPointerException null buffer * @throws IndexOutOfBoundsException on any invalid range. */ public static void validateReadArgs(byte[] buffer, int off, int len) { if (buffer == null) { throw new NullPointerException("Null byte array in"+ READ); } if (off < 0 ) { throw new IndexOutOfBoundsException("Negative buffer offset " + off + " in " + READ); } if (len < 0 ) { throw new IndexOutOfBoundsException("Negative read length " + len + " in " + READ); } if (off > buffer.length) { throw new IndexOutOfBoundsException("Buffer offset of " + off + "beyond buffer size of " + buffer.length + " in " + READ); } } } |
blob | long method | t | t | f | long method | blob | 0 | 10034 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-openstack/src/main/java/org/apache/hadoop/fs/swift/util/SwiftUtils.java/#L32-L216 | 1 | 1131 | 10034 | minor |
| 5146 | { "YES I found bad smells": true, "the bad smells are": [ "2. Data Class", "4. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | 2. data class, 4. long method | t | t | f | 2. data class, 4. long method | blob | 0 | 14395 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 1 | 5146 | 14395 | major |
| 2695 | YES I found bad smells the bad smells are: 1. Long method 2. Hardcoded values 3. Nested if statements and loops 4. Magic numbers 5. Unclear and inconsistent variable names 6. Lack of comments/documentation 7. Poor exception handling 8. Use of deprecated code and methods 9. Unused variables and imports | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | Long method2 Hardcoded values3 Nested if statements and loops4 Magic numbers5 Unclear and inconsistent variable names6 Lack of comments/documentation7 Poor exception handling8 Use of deprecated code and methods9 Unused variables and imports | t | f | f | . Long method2. Hardcoded values3. Nested if statements and loops4. Magic numbers5. Unclear and inconsistent variable names6. Lack of comments/documentation7. Poor exception handling8. Use of deprecated code and methods9. Unused variables and imports | blob | 0 | 15315 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 2 | 2695 | 15315 | minor |
| 101 | { "response": "YES I found bad smells", "bad smells are": [ "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class CountPageable implements Pageable { private Pageable delegate; public CountPageable(Pageable delegate) { this.delegate = delegate; } public int getPageNumber() { return delegate.getPageNumber(); } public int getPageSize() { return delegate.getPageSize(); } public long getOffset() { return delegate.getOffset(); } public Sort getSort() { // Sorting is not allowed on aggregate count queries. return Sort.unsorted(); } public Pageable next() { return delegate.next(); } public Pageable previousOrFirst() { return delegate.previousOrFirst(); } public Pageable first() { return delegate.first(); } public boolean hasPrevious() { return delegate.hasPrevious(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 1307 | https://github.com/spring-projects/spring-data-couchbase/blob/2f4500e9c76541bbbd6a612f7b9283d2455a2dc6/src/main/java/org/springframework/data/couchbase/repository/query/N1qlCountQueryCreator.java/#L83-L124 | 2 | 101 | 1307 | critical |
| 1153 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10135 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 1 | 1153 | 10135 | major |
| 5008 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | long method | t | t | f | long method | data class | 0 | 13770 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 5008 | 13770 | minor |
| 1870 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | long method | t | t | f | long method | blob | 0 | 12247 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 1 | 1870 | 12247 | major |
| 2492 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({"rawtypes", "unchecked"}) public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler { protected final JMXAgentContext agentContext; protected StandardMBean mbean; protected final AtomicLong trackedId = new AtomicLong(); /** * * @param agentContext * @param filter */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) { super(agentContext.getBundleContext(), filter, null); this.agentContext = agentContext; } /** * * @param agentContext * @param clazz */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) { super(agentContext.getBundleContext(), clazz, null); this.agentContext = agentContext; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Logger logger = agentContext.getLogger(); Object trackedService = null; long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); //API stipulates versions for compendium services with static ObjectName //This shouldn't happen but added as a consistency check if (trackedId.compareAndSet(0, serviceId)) { logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceId + "]"); trackedService = context.getService(reference); mbean = constructInjectMBean(trackedService); agentContext.registerMBean(AbstractCompendiumHandler.this); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed"); } return trackedService; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { Logger logger = agentContext.getLogger(); long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID); if (trackedId.compareAndSet(serviceID, 0)) { logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceID + "]"); agentContext.unregisterMBean(AbstractCompendiumHandler.this); context.ungetService(reference); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed"); } } private String getServiceDescription(ServiceReference reference) { String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION); if (serviceDescription == null) { Object obj = reference.getProperty(Constants.OBJECTCLASS); if (obj instanceof String[]) { StringBuilder sb = new StringBuilder(); for (String s : (String[]) obj) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } serviceDescription = sb.toString(); } else { serviceDescription = obj.toString(); } } return serviceDescription; } /** * Gets the StandardMBean managed by this handler when the backing service is available or null * * @see org.apache.aries.jmx.MBeanHandler#getMbean() */ public StandardMBean getMbean() { return mbean; } /** * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied * service tracked by this handler * * @param targetService * the compendium service tracked by this handler * @return The StandardMBean instance whose registration lifecycle will be managed by this handler */ protected abstract StandardMBean constructInjectMBean(Object targetService); /** * The base name of the MBean. Will be expanded with the framework name and the UUID. * @return */ protected abstract String getBaseName(); /** * @see org.apache.aries.jmx.MBeanHandler#getName() */ public String getName() { return ObjectNameUtils.createFullObjectName(context, getBaseName()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14622 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java/#L43-L166 | 2 | 2492 | 14622 | minor |
| 1613 | { "message": "YES, I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | t | f | f | long method | 0 | 11470 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 1613 | 11470 | minor | ||
| 331 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Expression setUpper(Bound newUpper) { upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive); return this; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 3397 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/index/sasi/plan/Expression.java/#L127-L131 | 1 | 331 | 3397 | minor |
| 2155 | YES I found bad smells the bad smells are: 1. Long method 2. Code duplication 3. Magic numbers 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | Long method2 Code duplication3 Magic numbers4 Feature envy | t | f | f | . Long method2. Code duplication3. Magic numbers4. Feature envy | data class | 0 | 13299 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 2 | 2155 | 13299 | minor |
| 1498 | YES, I found bad smells the bad smells are: 1. Long method list any bad smell. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
feature envy | Long methodlist any bad smellNO, I did not find any bad smell | t | f | f | . Long methodlist any bad smell.NO, I did not find any bad smell. | feature envy | 0 | 11127 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1498 | 11127 | minor |
| 2116 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Controller public class SignupController { private final SignupHelper signupHelper; @Inject public SignupController(AccountRepository accountRepository, SignedUpGateway gateway) { this.signupHelper = new SignupHelper(accountRepository, gateway); } /** * Render a signup form to the person as HTML in their web browser. */ @RequestMapping(value="/signup", method=RequestMethod.GET) public SignupForm signupForm(WebRequest request) { Connection connection = ProviderSignInUtils.getConnection(request); if (connection != null) { request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Greenhouse account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST); return SignupForm.fromProviderUser(connection.fetchUserProfile()); } else { return new SignupForm(); } } /** * Process a signup form submission. * Delegate to a {@link SignupHelper} to actually complete the signin transaction. * Redirects the new member to the application home page on successful sign-in. */ @RequestMapping(value="/signup", method=RequestMethod.POST) public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) { if (formBinding.hasErrors()) { return null; } boolean result = signupHelper.signup(form, formBinding, new SignupCallback() { public void postSignup(Account account) { ProviderSignInUtils.handlePostSignUp(account.getId().toString(), request); } }); return result ? "redirect:/" : null; } @RequestMapping(value="/signup", method=RequestMethod.POST, consumes="application/json") public ResponseEntity> signupFromApi(@RequestBody SignupForm form) { BindingResult formBinding = validate(form); // Temporary manual validation until SPR-9826 is fixed. if (formBinding.hasErrors()) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Validation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } boolean result = signupHelper.signup(form, formBinding); if (result) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account created"); return new ResponseEntity>(errorResponse, HttpStatus.CREATED); } else { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account creation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } } private BindException validate(SignupForm form) { BindException errors; errors = new BindException(form, "signupForm"); LazyValidatorFactory lvf = new LazyValidatorFactory(); Validator validator = new SpringValidatorAdapter(lvf.getValidator()); ValidationUtils.invokeValidator(validator, form, errors); return errors; } private List> getErrorsMap(BindingResult formBinding) { List fieldErrors = formBinding.getFieldErrors(); List> errors = new ArrayList>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map fieldErrorMap = new HashMap(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap); } return errors; } } |
blob | Long method2Feature envy | t | f | f | .Long method2.Feature envy | blob | 0 | 13195 | https://github.com/spring-projects/greenhouse/blob/c7994183812150de971ef4a76c08d5b4631ab5d1/src/main/java/com/springsource/greenhouse/signup/SignupController.java/#L54-L143 | 2 | 2116 | 13195 | minor |
| 2325 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14140 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 2325 | 14140 | minor |
| 181 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2064 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 181 | 2064 | critical |
| 3389 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6567 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 3389 | 6567 | minor |
| 1857 | YES I found bad smells the bad smells are: 1. Unnecessary comments 2. Duplicate code 3. Serialization of a class that doesn't implement Serializable 4. Poor naming conventions for variables and methods (e.g. "keys" and "nextMarker" are not descriptive) 5. Inconsistent use of return values in setters (some methods return a reference to the object and others do not) 6. Large method with multiple responsibilities 7. Feature envy (e.g. withKeys() method accesses a private variable and also has responsibility for setting it) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Unnecessary comments2 Duplicate code3 Serialization of a class that doesn't implement Serializable4 Poor naming conventions for variables and methods (eg "keys" and "nextMarker" are not descriptive)5 Inconsistent use of return values in setters (some methods return a reference to the object and others do not)6 Large method with multiple responsibilities 7 Feature envy (eg withKeys() method accesses a private variable and also has responsibility for setting it) | t | f | f | . Unnecessary comments2. Duplicate code3. Serialization of a class that doesn't implement Serializable4. Poor naming conventions for variables and methods (e.g. "keys" and "nextMarker" are not descriptive)5. Inconsistent use of return values in setters (some methods return a reference to the object and others do not)6. Large method with multiple responsibilities 7. Feature envy (e.g. withKeys() method accesses a private variable and also has responsibility for setting it) | data class | 0 | 12216 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 1857 | 12216 | major |
| 807 | {"message":"YES I found bad smells","bad smells are":["1.Long method","2.Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
blob | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | blob | 0 | 7626 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 807 | 7626 | minor |
| 530 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 5476 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 530 | 5476 | minor |
| 1950 | "YES I found bad smells" the bad smells are: 1. Poor variable and method naming conventions 2. No clear purpose or functionality for the class 3. Inconsistent use of constructor for both setting and getting ID and name 4. Excessive and repetitive code for setting and getting ID and name variables 5. No comments or documentation for the class or methods 6. No error handling for setting invalid values for ID or name 7. Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Poor variable and method naming conventions2 No clear purpose or functionality for the class3 Inconsistent use of constructor for both setting and getting ID and name 4 Excessive and repetitive code for setting and getting ID and name variables5 No comments or documentation for the class or methods6 No error handling for setting invalid values for ID or name7 Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality | t | f | f | . Poor variable and method naming conventions2. No clear purpose or functionality for the class3. Inconsistent use of constructor for both setting and getting ID and name 4. Excessive and repetitive code for setting and getting ID and name variables5. No comments or documentation for the class or methods6. No error handling for setting invalid values for ID or name7. Possible feature envy for the Book class as it only contains getters and setters for two variables, but it is not clear what its purpose is or if it has any additional functionality. | data class | 0 | 12530 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 1950 | 12530 | minor |
| 3848 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Code duplication, 4. High complexity, 5. Use of magic numbers, 6. Hidden dependencies, 7. Use of deprecated methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 30, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Thread) public static class DeleteTasksBenchmark { private StateManager manager; private Storage storage; private Set taskIds; @Param({"1000", "10000", "50000"}) private int numTasksToDelete; @Setup(Level.Trial) public void setUpStorage() { Injector injector = getInjector(); manager = injector.getInstance(StateManager.class); storage = injector.getInstance(Storage.class); storage.prepare(); } // JMH warns heavily against using `Invocation` but this test seems to meet the requirements // of using it. Each benchmark will take more than one ms and it avoids awkward logic to // setup storage before the benchmark. @Setup(Level.Invocation) public void setUp() { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(Storage.MutableStoreProvider storeProvider) throws RuntimeException { taskIds = bulkInsertTasks(numTasksToDelete, storeProvider.getUnsafeTaskStore()); } }); } @Benchmark public Set run() { return storage.write((Storage.MutateWork.Quiet>) storeProvider -> { manager.deleteTasks(storeProvider, taskIds); return taskIds; }); } } |
blob | Long method, 2 Feature envy,3 Code duplication,4 High complexity,5 Use of magic numbers,6 Hidden dependencies,7 Use of deprecated methods | t | f | f | . Long method, 2. Feature envy, 3. Code duplication, 4. High complexity, 5. Use of magic numbers, 6. Hidden dependencies, 7. Use of deprecated methods. | blob | 0 | 9985 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/jmh/java/org/apache/aurora/benchmark/StateManagerBenchmarks.java/#L117-L159 | 2 | 3848 | 9985 | minor |
| 455 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | long method | t | t | f | long method | blob | 0 | 4445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 1 | 455 | 4445 | minor |
| 1380 | {"response":"YES I found bad smells","the bad smells are":["1. Long Method","2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | '1. Long Method', '2. Data Class' | t | t | f | {',1,.," ",L,o,n,g," ",M,e,t,h,o,d,',","," ",',2,.," ",D,a,t,a," ",C,l,a,s,s,'} | {',1,.," ",o,n,g," ",M,t,h,o,d,',","," ",',2,.," ",D,t," ",C,'} | 0 | 10819 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 1 | 1380 | 10819 | major |
| 1793 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11996 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 1793 | 11996 | critical |
| 90 | {"message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class TestConfiguration { private String downloadUrl; private final String description; private TestSuite suite; public TestConfiguration(String description) { this.description = description; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getDescription() { return description; } @Override public String toString() { return getClass().getSimpleName() + " [" + description + "]"; } public TestSuite createSuite(TestSuite parentSuite) { suite = new TestSuite("Testing on " + getDescription()); parentSuite.addTest(suite); suite.addTest(new Activation("TestSuite: " + getDescription(), true)); return suite; } public void add(Class clazz) { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTestSuite(clazz); } public void done() { Assert.isNotNull(suite, "Invoke createSuite() first"); suite.addTest(new Activation("done", false)); suite = null; } private final class Activation extends TestCase { private final boolean activate; private Activation(String name, boolean activate) { super(name); this.activate = activate; } @Override protected void runTest() throws Throwable { if (activate) { activate(); } else { getDefault().activate(); } } } protected abstract TestConfiguration getDefault(); public abstract void activate(); public abstract TestHarness createHarness(); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1240 | https://github.com/spring-projects/eclipse-integration-tcserver/blob/5b381256cb35cfe2aa21f5093558f7ca927c289f/com.vmware.vfabric.ide.eclipse.tcserver.tests/src/com/vmware/vfabric/ide/eclipse/tcserver/tests/support/TestConfiguration.java/#L21-L95 | 2 | 90 | 1240 | major |
| 155 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1952 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 1 | 155 | 1952 | major |
| 1285 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10608 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 1285 | 10608 | critical |
| 1351 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10757 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 1 | 1351 | 10757 | minor |
| 2665 | YES I found bad smells the bad smells are: 1. Code duplication 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | Code duplication2 Long method 3 Feature envy | t | f | f | . Code duplication2. Long method 3. Feature envy | data class | 0 | 15202 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 2665 | 15202 | minor |
| 580 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers/numbers used without explanation (such as "1" or "0") 3. Use of abbreviations instead of descriptive variable names (such as "tikaInputStream" instead of "tikaInputStreamReader") 4. Mixing of different responsibilities (parsing, handling metadata, creating and returning a result map) 5. Lack of proper error handling or exception handling (only a generic "throws" statement and a basic "try-catch" block in one section) 6. Excessive comments and lack of meaningful comments describing what the code does 7. Possible feature envy due to the use of "metadata.names()" and "metadata.getValues(key)" multiple times in the same method 8. Inefficient string concatenation ("dataBuilder.append(val)") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | Long method2 Magic numbers/numbers used without explanation (such as " | t | f | f | . Long method2. Magic numbers/numbers used without explanation (such as " | feature envy | 0 | 5785 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 580 | 5785 | minor |
| 1821 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static final class TomcatInjections { // load when needed private TomcatInjections() { // no-op } private static Map> buildInjectionMap(final NamingResourcesImpl namingResources) { final Map> injectionMap = new HashMap<>(); for (final Injectable resource : namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private static void addInjectionTarget(final Injectable resource, final Map> injectionMap) { final List injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && !injectionTargets.isEmpty()) { final String jndiName = resource.getName(); for (final InjectionTarget injectionTarget : injectionTargets) { final String clazz = injectionTarget.getTargetClass(); Map injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 12097 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/JavaeeInstanceManager.java/#L316-L362 | 1 | 1821 | 12097 | minor |
| 2237 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13612 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 2237 | 13612 | minor |
| 559 | { "message": "YES I found bad smells" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuckAddDependencyIntention extends BaseIntentionAction { private static Logger LOGGER = Logger.getInstance(BuckAddDependencyIntention.class); /** * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the * given reference element to those of the given psiClass. * * Note that this intention can fail to be created if either side of the edge cannot be * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking * this intention may fail to create edges in either the Buck target graph or the IntelliJ module * graph (or both). */ @Nullable public static BuckAddDependencyIntention create( PsiJavaCodeReferenceElement referenceElement, PsiClass psiClass) { VirtualFile editSourceFile = referenceElement.getContainingFile().getVirtualFile(); if (editSourceFile == null) { return null; } Project project = referenceElement.getProject(); BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); VirtualFile editBuildFile = buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null); if (editBuildFile == null) { return null; } VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile(); if (importSourceFile == null) { return null; } VirtualFile importBuildFile = buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null); if (importBuildFile == null) { return null; } if (importBuildFile.equals(editBuildFile)) { return null; } ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); Module editModule = projectFileIndex.getModuleForFile(editSourceFile); if (editModule == null) { return null; } Module importModule = projectFileIndex.getModuleForFile(importSourceFile); if (importModule == null) { return null; } BuckTarget editSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(editSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (editSourceTarget == null) { return null; } BuckTarget importSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(importSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (importSourceTarget == null) { return null; } return new BuckAddDependencyIntention( project, referenceElement, editBuildFile, editSourceFile, editSourceTarget, editModule, psiClass, importBuildFile, importSourceFile, importSourceTarget, importModule); } private Project project; // Fields pertaining to the element in the file being edited private PsiJavaCodeReferenceElement referenceElement; private VirtualFile editBuildFile; private VirtualFile editSourceFile; private BuckTarget editSourceTarget; private BuckTarget editTarget; private Module editModule; // Fields pertaining to the dependency that should be resolved/imported private PsiClass psiClass; private VirtualFile importBuildFile; private VirtualFile importSourceFile; private BuckTarget importSourceTarget; private BuckTarget importTarget; private Module importModule; BuckAddDependencyIntention( Project project, PsiJavaCodeReferenceElement referenceElement, VirtualFile editBuildFile, VirtualFile editSourceFile, BuckTarget editSourceTarget, Module editModule, PsiClass psiClass, VirtualFile importBuildFile, VirtualFile importSourceFile, BuckTarget importSourceTarget, Module importModule) { this.project = project; this.referenceElement = referenceElement; this.editBuildFile = editBuildFile; this.editSourceFile = editSourceFile; this.editSourceTarget = editSourceTarget; this.editModule = editModule; this.psiClass = psiClass; this.importBuildFile = importBuildFile; this.importSourceFile = importSourceFile; this.importSourceTarget = importSourceTarget; this.importModule = importModule; String message = "Add BUCK dependency on owner(" + importSourceTarget + ")"; setText(message); } @Nls(capitalization = Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return this.getClass().getSimpleName(); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { String msg = "Invoked for project " + project.getName() + " and file " + psiFile.getName(); LOGGER.info(msg); queryBuckForTargets(editor); } /** Helper class to handle deserialization of buck query. */ static class TargetMetadata { public BuckTarget target; public @Nullable List deps; public @Nullable List visibility; // null means PUBLIC public @Nullable List srcs; public @Nullable List resources; static TargetMetadata from( BuckTargetLocator buckTargetLocator, BuckTarget target, JsonObject payload) { TargetMetadata targetMetadata = new TargetMetadata(); targetMetadata.target = target; targetMetadata.srcs = stringListOrNull(payload.get("srcs")); targetMetadata.resources = stringListOrNull(payload.get("resources")); // Deps are a list of BuckTargets targetMetadata.deps = Optional.ofNullable(stringListOrNull(payload.get("deps"))) .map( deps -> deps.stream() .map( s -> BuckTarget.parse(s).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList())) .orElse(null); // Visibilility falls in one of three cases: // (1) if unspecified => means visibility is limited to the current package // (2) contains "PUBLIC" => available everywhere // (3) otherwise is a list of buck target patterns where it is visible List optionalVisibility = stringListOrNull(payload.get("visibility")); if (optionalVisibility == null) { targetMetadata.visibility = Collections.singletonList(target.asPattern().asPackageMatchingPattern()); } else if (optionalVisibility.contains("PUBLIC")) { targetMetadata.visibility = null; // } else { targetMetadata.visibility = optionalVisibility .stream() .map(p -> BuckTargetPattern.parse(p).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList()); } return targetMetadata; } static @Nullable List stringListOrNull(@Nullable JsonElement jsonElement) { if (jsonElement == null) { return null; } return new Gson().fromJson(jsonElement, new TypeToken>() {}.getType()); } boolean isVisibleTo(BuckTarget target) { if (visibility == null) { return true; } return visibility.stream().anyMatch(pattern -> pattern.matches(target)); } boolean hasDependencyOn(BuckTarget target) { return deps.stream().anyMatch(dep -> dep.equals(target)); } boolean contains(BuckTarget targetFile) { if (!target.asPattern().asPackageMatchingPattern().matches(targetFile)) { return false; } String relativeToBuildFile = targetFile.getRuleName(); return srcs.contains(relativeToBuildFile) || resources.contains(relativeToBuildFile); } } /** Queries buck for targets that own the editSourceFile and the importSourceFile. */ private void queryBuckForTargets(Editor editor) { BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); String editPath = editSourceFile.getPath(); String importPath = importSourceFile.getPath(); BuckJsonCommandHandler> handler = new BuckJsonCommandHandler<>( project, BuckCommand.QUERY, new Callback>() { @Override public List deserialize(JsonElement jsonElement) throws IOException { Type type = new TypeToken>() {}.getType(); Map raw = new Gson().fromJson(jsonElement, type); List results = new ArrayList<>(); for (Entry entry : raw.entrySet()) { BuckTarget.parse(entry.getKey()) .map(buckTargetLocator::resolve) .map( target -> TargetMetadata.from(buckTargetLocator, target, entry.getValue())) .ifPresent(results::add); } return results; } @Override public void onSuccess(List results, String stderr) { List editTargets = new ArrayList<>(); List importTargets = new ArrayList<>(); for (TargetMetadata targetMetadata : results) { if (targetMetadata.contains(editSourceTarget)) { editTargets.add(targetMetadata); } if (targetMetadata.contains(importSourceTarget)) { importTargets.add(targetMetadata); } } updateDependencies(editor, editTargets, importTargets); } @Override public void onFailure( String stdout, String stderr, @Nullable Integer exitCode, @Nullable Throwable throwable) { BuckNotification.getInstance(project) .showWarningBalloon( "Could not determine owners for " + editSourceFile + " and/or " + importSourceFile); return; } }); handler .command() .addParameters( "owner(%s)", editPath, importPath, "--output-attributes=deps|srcs|visibility|resources"); handler.runInCurrentThreadPostEnd(() -> {}); } /** * Implementation of {@link * com.intellij.notification.NotificationListener#hyperlinkUpdate(Notification, HyperlinkEvent)}. */ private void hyperlinkActivated( @NotNull Notification notification, @NotNull HyperlinkEvent event) { String href = event.getDescription(); switch (href) { case "editTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(editTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "editBuildFile": FileEditorManager.getInstance(project).openFile(editBuildFile, true); break; case "editSourceFile": FileEditorManager.getInstance(project).openFile(editSourceFile, true); break; case "importTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(importTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "importBuildFile": FileEditorManager.getInstance(project).openFile(importBuildFile, true); break; case "importSourceFile": FileEditorManager.getInstance(project).openFile(importSourceFile, true); break; } } private void updateDependencies( Editor editor, List editTargets, List importTargets) { if (editTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + editSourceTarget + " in " + editBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (importTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + importSourceTarget + " in " + importBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } TargetMetadata editTargetMetadata = editTargets.get(0); TargetMetadata importTargetMetadata = importTargets.get(0); editTarget = editTargetMetadata.target; importTarget = importTargetMetadata.target; if (!importTargetMetadata.isVisibleTo(editTarget)) { String message = "Add dependency failed: The target " + importTarget + " is not visible to " + editTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (!editTargetMetadata.hasDependencyOn(importTarget)) { if (!BuckDeps.modifyTargetToAddDependency( editBuildFile, editTarget.toString(), importTarget.toString())) { String message = "Add dependency failed: Could not add modify build file for " + editTarget + " to add dependency on " + importTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } } else { String message = "No need to modify build file " + editBuildFile + ", already has dependency from " + editTarget + " to " + importTarget + ""; BuckNotification.getInstance(project).showInfoBalloon(message, this::hyperlinkActivated); } ModuleRootModificationUtil.updateModel( editModule, (modifiableRootModel -> { if (modifiableRootModel.findModuleOrderEntry(importModule) != null) { LOGGER.info( "No need to modify module " + editModule.getName() + ", already has dependency on " + importModule.getName()); } else { modifiableRootModel.addModuleOrderEntry(importModule); LOGGER.info( "Successfully added module dependency from " + editModule.getName() + " on " + importModule.getName()); } new AddImportAction(project, referenceElement, editor, psiClass).execute(); })); } } |
blob | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 5627 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/autodeps/BuckAddDependencyIntention.java/#L66-L480 | 2 | 559 | 5627 | major |
| 2595 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15005 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 2595 | 15005 | major |
| 1838 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | Long Method, Data Class | t | f | f | Long Method, Data Class | feature envy | 0 | 12143 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 1838 | 12143 | minor |
| 1712 | {"output": "YES I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | t | f | f | data class | 0 | 11772 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1712 | 11772 | minor | ||
| 557 | YES, I found bad smells The following bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5616 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 2 | 557 | 5616 | minor |
| 962 | { "message": "YES I found bad smells", "bad smells are": [ "3. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
feature envy | 3. long method | t | t | f | 3. long method | feature envy | 0 | 8570 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 962 | 8570 | minor |
| 836 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7756 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 1 | 836 | 7756 | major |
| 1872 | { "response": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
blob | data class | t | t | f | data class | blob | 0 | 12250 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 1872 | 12250 | minor |
| 2771 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Long method2 Duplicate code | t | f | f | . Long method2. Duplicate code | data class | 0 | 1068 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 2771 | 1068 | major |
| 1876 | YES I found bad smells, the bad smells are: 1.Long method, 2.Magic number, 3.Feature envy, 4.Data class, 5.Unclear naming conventions, 6.Redundant code, 7.Missing comments/documentation, 8.Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
blob | Long method, 2Magic number, 3Feature envy,4Data class,5Unclear naming conventions,6Redundant code,7Missing comments/documentation,8Code duplication | t | f | f | .Long method, 2.Magic number, 3.Feature envy, 4.Data class, 5.Unclear naming conventions, 6.Redundant code, 7.Missing comments/documentation, 8.Code duplication | blob | 0 | 12264 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 1876 | 12264 | minor |
| 1939 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 1 | 1939 | 12479 | major |
| 1462 | YES, I found bad smells: 1. Long method 2. Feature envy 3. Primitive obsession 4. Data class 5. Poor encapsulation 6. Redundant fields 7. Duplicate code and functionality in methods 8. Inconsistent variable naming 9. Lack of comments and documentation 10. Poor naming conventions for methods and variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
blob | Long method2 Feature envy3 Primitive obsession4 Data class5 Poor encapsulation6 Redundant fields7 Duplicate code and functionality in methods8 Inconsistent variable naming9 Lack of comments and documentation | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Data class5. Poor encapsulation6. Redundant fields7. Duplicate code and functionality in methods8. Inconsistent variable naming9. Lack of comments and documentation | blob | 0 | 11026 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 1462 | 11026 | major |
| 2690 | {"response":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 15292 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 2690 | 15292 | minor |
| 1392 | YES, I found bad smells the bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy. | blob | 0 | 10844 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 2 | 1392 | 10844 | minor |
| 2035 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 12828 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 2035 | 12828 | minor |
| 1535 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11218 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 1535 | 11218 | minor |
| 2601 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15019 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 2601 | 15019 | major |
| 2034 | YES I found bad smells the bad smells are: 1. Public access modifier for inner class 2. Non-descriptive class and method names 3. Abstract method with no implementation 4. Abstract class with no non-abstract methods 5. Lack of comments/documentation 6. Class not following standard Java naming conventions (missing CamelCase) 7. Lack of proper encapsulation of fields in inner class 8. Use of static class for no apparent reason | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | Public access modifier for inner class2 Non-descriptive class and method names3 Abstract method with no implementation4 Abstract class with no non-abstract methods5 Lack of comments/documentation6 Class not following standard Java naming conventions (missing CamelCase)7 Lack of proper encapsulation of fields in inner class8 Use of static class for no apparent reason | t | f | f | . Public access modifier for inner class2. Non-descriptive class and method names3. Abstract method with no implementation4. Abstract class with no non-abstract methods5. Lack of comments/documentation6. Class not following standard Java naming conventions (missing CamelCase)7. Lack of proper encapsulation of fields in inner class8. Use of static class for no apparent reason | data class | 0 | 12827 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 2 | 2034 | 12827 | minor |
| 3618 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface JsonObjectMapper { default String toJson(Object value) throws IOException { return null; } default void toJson(Object value, Writer writer) throws IOException { } default N toJsonNode(Object value) throws IOException { return null; } default T fromJson(Object json, Class valueType) throws IOException { return null; } /** * Deserialize a JSON to an expected {@link ResolvableType}. * @param json the JSON to deserialize * @param valueType the {@link ResolvableType} for the target object. * @param the expected object type * @return deserialization result object * @throws IOException a JSON parsing exception * @since 5.2 */ default T fromJson(Object json, ResolvableType valueType) throws IOException { return null; } default T fromJson(Object json, Map javaTypes) throws IOException { return null; } default T fromJson(P parser, Type valueType) throws IOException { return null; } default void populateJavaTypes(Map map, Object object) { Class targetClass = object.getClass(); Class contentClass = null; Class keyClass = null; map.put(JsonHeaders.TYPE_ID, targetClass); if (object instanceof Collection && !((Collection) object).isEmpty()) { Object firstElement = ((Collection) object).iterator().next(); if (firstElement != null) { contentClass = firstElement.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } } if (object instanceof Map && !((Map) object).isEmpty()) { Object firstValue = ((Map) object).values().iterator().next(); if (firstValue != null) { contentClass = firstValue.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } Object firstKey = ((Map) object).keySet().iterator().next(); if (firstKey != null) { keyClass = firstKey.getClass(); map.put(JsonHeaders.KEY_TYPE_ID, keyClass); } } map.put(JsonHeaders.RESOLVABLE_TYPE, buildResolvableType(targetClass, contentClass, keyClass)); } static ResolvableType buildResolvableType(Class targetClass, @Nullable Class contentClass, @Nullable Class keyClass) { if (keyClass != null) { return TypeDescriptor .map(targetClass, TypeDescriptor.valueOf(keyClass), TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else if (contentClass != null) { return TypeDescriptor .collection(targetClass, TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else { return ResolvableType.forClass(targetClass); } } } |
blob | data class | t | t | f | data class | blob | 0 | 8109 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-core/src/main/java/org/springframework/integration/support/json/JsonObjectMapper.java/#L41-L130 | 1 | 3618 | 8109 | minor |
| 2226 | YES I found bad smells the bad smells are: 1. Duplicate code (in the getEncodedKey and getEncodedValue methods). 2. Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class). 3. Poor naming conventions (the variable names "key" and "val" are not descriptive). 4. Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets). 5. Lack of comments or documentation (no explanation of the purpose or functionality of the code). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Duplicate code (in the getEncodedKey and getEncodedValue methods)2 Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class)3 Poor naming conventions (the variable names "key" and "val" are not descriptive)4 Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets)5 Lack of comments or documentation (no explanation of the purpose or functionality of the code) | t | f | f | . Duplicate code (in the getEncodedKey and getEncodedValue methods).2. Feature envy (The Header class is too focused on the key and value properties, which should instead be encapsulated in a separate class).3. Poor naming conventions (the variable names "key" and "val" are not descriptive).4. Inconsistent formatting and spacing (lack of indentation and inconsistent placement of brackets).5. Lack of comments or documentation (no explanation of the purpose or functionality of the code). | data class | 0 | 13576 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 2226 | 13576 | major |
| 808 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ScriptValueImpl extends ActionValueImpl implements ScriptValue { /** * The default value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected static final String SCRIPT_EDEFAULT = null; /** * The cached value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected String script = SCRIPT_EDEFAULT; /** * * @generated */ protected ScriptValueImpl( ) { super( ); } /** * * @generated */ @Override protected EClass eStaticClass( ) { return AttributePackage.Literals.SCRIPT_VALUE; } /** * * @generated */ public String getScript( ) { return script; } /** * * @generated */ public void setScript( String newScript ) { String oldScript = script; script = newScript; if ( eNotificationRequired( ) ) eNotify( new ENotificationImpl( this, Notification.SET, AttributePackage.SCRIPT_VALUE__SCRIPT, oldScript, script ) ); } /** * * * @generated */ @Override public Object eGet( int featureID, boolean resolve, boolean coreType ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return getScript( ); } return super.eGet( featureID, resolve, coreType ); } /** * * * @generated */ @Override public void eSet( int featureID, Object newValue ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( (String) newValue ); return; } super.eSet( featureID, newValue ); } /** * * * @generated */ @Override public void eUnset( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( SCRIPT_EDEFAULT ); return; } super.eUnset( featureID ); } /** * * * @generated */ @Override public boolean eIsSet( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return SCRIPT_EDEFAULT == null ? script != null : !SCRIPT_EDEFAULT.equals( script ); } return super.eIsSet( featureID ); } /** * * @generated */ @Override public String toString( ) { if ( eIsProxy( ) ) return super.toString( ); StringBuffer result = new StringBuffer( super.toString( ) ); result.append( " (script: " ); //$NON-NLS-1$ result.append( script ); result.append( ')' ); return result.toString( ); } /** * A convenience method provided to build a script action value when needed * * @param script * @return */ public static final ScriptValue create( String script ) { ScriptValue sv = AttributeFactory.eINSTANCE.createScriptValue( ); sv.setScript( script ); return sv; } /** * A convenient method to get an instance copy. This is much faster than the * ECoreUtil.copy(). */ public ScriptValue copyInstance( ) { ScriptValueImpl dest = new ScriptValueImpl( ); dest.set( this ); return dest; } protected void set( ScriptValue src ) { super.set( src ); script = src.getScript( ); } /* * Get script expression. * * @return expression the script expression. */ public ScriptExpression getScriptExpression( ) { ScriptExpression expression = new ScriptExpression( ); expression.setType( ChartUtil.getExpressionType( script ) ); expression.setValue( ChartUtil.getExpressionText( script ) ); return expression; } /* * Set script expression. * * @param expression the script expression. */ public void setScriptExpression( ScriptExpression expression ) { setScript( ChartUtil.adaptExpression( expression ) ); } } // ScriptValueImpl |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7627 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/model/attribute/impl/ScriptValueImpl.java/#L35-L237 | 2 | 808 | 7627 | minor |
| 1517 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 11166 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 2 | 1517 | 11166 | minor |
| 1189 | {"response": "YES I found bad smells", "the bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
blob | long method | t | t | f | long method | blob | 0 | 10250 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 2 | 1189 | 10250 | major |
| 274 | { "response": "NO, I did not find any bad smell" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2936 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 274 | 2936 | critical | ||
| 1368 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10790 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 2 | 1368 | 10790 | minor |
| 1161 | YES I found bad smells the bad smells are: 1. Magic numbers - the value -3096346807579L is a magic number and should be replaced with a named constant. 2. Constructor containing mostly assignment operations - the constructor only contains assignment operations, indicating that it could possibly be refactored into a method or removed altogether. 3. Lack of encapsulation - the instance variables numCores and maxMemory are declared as public, making them accessible to outside classes. This violates the principle of encapsulation and could lead to unexpected behavior. 4. Inconsistent variable naming - the variables numCores and maxMemory have different naming styles, making the code harder to read and potentially confusing for other developers. 5. Class name not descriptive - the class name "SysInfo" is not very descriptive and could be improved to better reflect its purpose. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
blob | Magic numbers - the value -3096346807579L is a magic number and should be replaced with a named constant2 Constructor containing mostly assignment operations - the constructor only contains assignment operations, indicating that it could possibly be refactored into a method or removed altogether 3 Lack of encapsulation - the instance variables numCores and maxMemory are declared as public, making them accessible to outside classes This violates the principle of encapsulation and could lead to unexpected behavior4 Inconsistent variable naming - the variables numCores and maxMemory have different naming styles, making the code harder to read and potentially confusing for other developers5 Class name not descriptive - the class name "SysInfo" is not very descriptive and could be improved to better reflect its purpose | t | f | f | . Magic numbers - the value -3096346807579L is a magic number and should be replaced with a named constant.2. Constructor containing mostly assignment operations - the constructor only contains assignment operations, indicating that it could possibly be refactored into a method or removed altogether. 3. Lack of encapsulation - the instance variables numCores and maxMemory are declared as public, making them accessible to outside classes. This violates the principle of encapsulation and could lead to unexpected behavior.4. Inconsistent variable naming - the variables numCores and maxMemory have different naming styles, making the code harder to read and potentially confusing for other developers.5. Class name not descriptive - the class name "SysInfo" is not very descriptive and could be improved to better reflect its purpose. | blob | 0 | 10165 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 1161 | 10165 | minor |
| 49 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 856 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 1 | 49 | 856 | minor |
| 1936 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12467 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 1 | 1936 | 12467 | major | ||
| 969 | {"message": "YES I found bad smells", "bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | blob | t | t | f | blob | data class | 0 | 8680 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 1 | 969 | 8680 | major |
| 1458 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | long method | t | t | f | long method | blob | 0 | 11018 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 1 | 1458 | 11018 | minor |
| 1634 | {"message": "YES I found bad smells", "bad smells are": "Blob, Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
blob | t | f | f | blob | 0 | 11515 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 1634 | 11515 | major | ||
| 2062 | { "message": "YES I found bad smells", "bad smells are": "2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | 2. data class | t | t | f | 2. data class | long method | 0 | 12975 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 1 | 2062 | 12975 | major |
| 1366 | the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | f | f | f | . Long method | data class | 0 | 10787 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 1366 | 10787 | major |
| 1946 | YES I found bad smells the bad smells are: 1. Long method - the methods in this class are quite long and could potentially be broken down into smaller, more specific methods. 2. Feature envy - the methods in this class are heavily reliant on accessing the internals of other classes, indicating that they may not be in the correct class and could be better placed in another class. 3. Magic numbers/strings - the use of hard-coded strings and numbers throughout the code can make it difficult to read and maintain. 4. Inconsistent formatting - the indentation is inconsistent throughout the code, making it difficult to read and understand. 5. Misleading naming - the class is named "ObserveUtil" but it contains methods that create observations as well as validate them, making its purpose unclear. 6. Violation of Single Responsibility Principle - the class handles multiple responsibilities, including creating observations, extracting information from observations, and validating observations. It would be better to separate these responsibilities into different classes to improve maintainability and readability. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObserveUtil { /* keys used to populate the request context */ public static final String CTX_ENDPOINT = "leshan-endpoint"; public static final String CTX_REGID = "leshan-regId"; public static final String CTX_LWM2M_PATH = "leshan-path"; /** * Create a LWM2M observation from a CoAP request. */ public static Observation createLwM2mObservation(Request request) { String regId = null; String lwm2mPath = null; Map context = null; for (Entry ctx : request.getUserContext().entrySet()) { switch (ctx.getKey()) { case CTX_REGID: regId = ctx.getValue(); break; case CTX_LWM2M_PATH: lwm2mPath = ctx.getValue(); break; case CTX_ENDPOINT: break; default: if (context == null) { context = new HashMap<>(); } context.put(ctx.getKey(), ctx.getValue()); } } ContentFormat contentFormat = null; if (request.getOptions().hasAccept()) { contentFormat = ContentFormat.fromCode(request.getOptions().getAccept()); } return new Observation(request.getToken().getBytes(), regId, new LwM2mPath(lwm2mPath), contentFormat, context); } /** * Create a CoAP observe request context with specific keys needed for internal Leshan working. */ public static Map createCoapObserveRequestContext(String endpoint, String registrationId, ObserveRequest request) { Map context = new HashMap<>(); context.put(CTX_ENDPOINT, endpoint); context.put(CTX_REGID, registrationId); context.put(CTX_LWM2M_PATH, request.getPath().toString()); for (Entry ctx : request.getContext().entrySet()) { context.put(ctx.getKey(), ctx.getValue()); } return context; } public static String extractRegistrationId(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_REGID); } public static String extractLwm2mPath(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_LWM2M_PATH); } public static String extractEndpoint(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_ENDPOINT); } /** * Validate the Californium observation. It is valid if it contains all necessary context for Leshan. */ public static String validateCoapObservation(org.eclipse.californium.core.observe.Observation observation) { if (!observation.getRequest().getUserContext().containsKey(CTX_REGID)) throw new IllegalStateException("missing registrationId info in the request context"); if (!observation.getRequest().getUserContext().containsKey(CTX_LWM2M_PATH)) throw new IllegalStateException("missing lwm2m path info in the request context"); String endpoint = observation.getRequest().getUserContext().get(CTX_ENDPOINT); if (endpoint == null) throw new IllegalStateException("missing endpoint info in the request context"); return endpoint; } } |
blob | Long method - the methods in this class are quite long and could potentially be broken down into smaller, more specific methods2 Feature envy - the methods in this class are heavily reliant on accessing the internals of other classes, indicating that they may not be in the correct class and could be better placed in another class3 Magic numbers/strings - the use of hard-coded strings and numbers throughout the code can make it difficult to read and maintain4 Inconsistent formatting - the indentation is inconsistent throughout the code, making it difficult to read and understand5 Misleading naming - the class is named "ObserveUtil" but it contains methods that create observations as well as validate them, making its purpose unclear6 Violation of Single Responsibility Principle - the class handles multiple responsibilities, including creating observations, extracting information from observations, and validating observations It would be better to separate these responsibilities into different classes to improve maintainability and readability | t | f | f | . Long method - the methods in this class are quite long and could potentially be broken down into smaller, more specific methods.2. Feature envy - the methods in this class are heavily reliant on accessing the internals of other classes, indicating that they may not be in the correct class and could be better placed in another class.3. Magic numbers/strings - the use of hard-coded strings and numbers throughout the code can make it difficult to read and maintain.4. Inconsistent formatting - the indentation is inconsistent throughout the code, making it difficult to read and understand.5. Misleading naming - the class is named "ObserveUtil" but it contains methods that create observations as well as validate them, making its purpose unclear.6. Violation of Single Responsibility Principle - the class handles multiple responsibilities, including creating observations, extracting information from observations, and validating observations. It would be better to separate these responsibilities into different classes to improve maintainability and readability. | blob | 0 | 12519 | https://github.com/eclipse/leshan/blob/eb75fc8b7d5560944e6d532f1a09d5e5c6e54559/leshan-server-cf/src/main/java/org/eclipse/leshan/server/californium/ObserveUtil.java/#L32-L114 | 2 | 1946 | 12519 | minor |
| 4052 | YES I found bad smells the bad smells are: 1. Long method 2. Commented out code 3. Complex conditional logic 4. Project-specific variable names 5. Unused variables 6. Multiple responsibilities 7. Debug logging statements 8. Side effects within method 9. Lack of abstraction/modularity 10. Magic numbers/constants 11. Inadequate comments/documentation 12. Excessive use of types and casting 13. Mutable state 14. Hard-coded values 15. Unused imports | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
feature envy | Long method2 Commented out code3 Complex conditional logic 4 Project-specific variable names 5 Unused variables6 Multiple responsibilities 7 Debug logging statements8 Side effects within method9 Lack of abstraction/modularity | t | f | f | . Long method2. Commented out code3. Complex conditional logic 4. Project-specific variable names 5. Unused variables6. Multiple responsibilities 7. Debug logging statements8. Side effects within method9. Lack of abstraction/modularity | feature envy | 0 | 10701 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 4052 | 10701 | minor |
| 2537 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BrocadeVcsApi { private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class); private final String _host; private final String _adminuser; private final String _adminpass; protected DefaultHttpClient _client; protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { String url; try { url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Brocade Switch API URL", e); throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); } if ("post".equalsIgnoreCase(type)) { return new HttpPost(url); } else if ("get".equalsIgnoreCase(type)) { return new HttpGet(url); } else if ("delete".equalsIgnoreCase(type)) { return new HttpDelete(url); } else if ("patch".equalsIgnoreCase(type)) { return new HttpPatch(url); } else { throw new BrocadeVcsApiException("Requesting unknown method type"); } } public BrocadeVcsApi(String address, String username, String password) { _host = address; _adminuser = username; _adminpass = password; _client = new DefaultHttpClient(); _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); } /* * Get Operational Status */ public Output getSwitchStatus() throws BrocadeVcsApiException { return executeRetreiveStatus(Constants.STATUS_URI); } /* * Creates a new virtual network. */ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (createInterfaceVlan(vlanId)) { final PortProfile portProfile = createPortProfile(vlanId, networkId); if (portProfile != null) { return activatePortProfile(portProfile); } } return false; } /* * Activates a port-profile. */ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); portProfile.setVlanProfile(null); final Activate activate = new Activate(); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Creates AMPP port-profile. */ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); if (executeCreateObject(portProfile, Constants.URI)) { if (createVlanSubProfile(vlanId, portProfile)) { return portProfile; } } return null; } /* * Create vlan sub-profile for port-profile */ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final VlanProfile vlanProfile = new VlanProfile(); portProfile.setVlanProfile(vlanProfile); if (executeUpdateObject(portProfile, Constants.URI)) { return configureVlanSubProfile(vlanId, portProfile); } return false; } /* * Configures vlan sub-profile for port-profile. * - configure L2 mode for vlan sub-profile * - configure trunk mode for vlan sub-profile * - configure allowed VLANs for vlan sub-profile */ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final SwitchportBasic switchPortBasic = new SwitchportBasic(); final Basic basic = new Basic(); switchPortBasic.setBasic(basic); portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); // configure L2 mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { VlanProfile vlanProfile = new VlanProfile(); Switchport switchPort = new Switchport(); final Mode mode = new Mode(); mode.setVlanMode("trunk"); switchPort.setMode(mode); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); // configure trunk mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { vlanProfile = new VlanProfile(); switchPort = new Switchport(); final Trunk trunk = new Trunk(); final Allowed allowed = new Allowed(); final Allowed.Vlan allowedVlan = new Allowed.Vlan(); allowedVlan.setAdd(vlanId); allowed.setVlan(allowedVlan); trunk.setAllowed(allowed); switchPort.setTrunk(trunk); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); //configure allowed VLANs for vlan sub-profile return executeUpdateObject(portProfile, Constants.URI); } } return false; } /* * Creates a vlan interface. */ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Associates a MAC address to virtual network. */ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Disassociates a MAC address from virtual network. */ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setOperation("delete"); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes a new virtual network. */ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (deactivatePortProfile(networkId)) { if (deletePortProfile(networkId)) { return deleteInterfaceVlan(vlanId); } } return false; } /* * Deletes a vlan interface. */ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setOperation("delete"); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Deactivates a port-profile. */ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Activate activate = new Activate(); activate.setOperation("delete"); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes AMPP port-profile. */ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); portProfile.setOperation("delete"); //deletes port-profile return executeUpdateObject(portProfile, Constants.URI); } protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { final boolean result = true; if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpPatch pm = (HttpPatch)createMethod("patch", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to update object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); return result; } protected String convertToString(T object) throws BrocadeVcsApiException { final StringWriter stringWriter = new StringWriter(); try { final JAXBContext context = JAXBContext.newInstance(object.getClass()); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, stringWriter); } catch (final JAXBException e) { s_logger.error("Failed to convert object to string : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); } final String str = stringWriter.toString(); s_logger.info(str); return str; } protected Output convertToXML(String object) throws BrocadeVcsApiException { Output output = null; try { final JAXBContext context = JAXBContext.newInstance(Output.class); final StringReader reader = new StringReader(object); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(reader); if (result instanceof Output) { output = (Output)result; s_logger.info(output); } } catch (final JAXBException e) { s_logger.error("Failed to convert string to object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); } return output; } protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final boolean result = true; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to create object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return result; } protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while ((readLine = br.readLine()) != null) { s_logger.debug(readLine); sb.append(readLine); } } catch (final Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); } protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpDelete dm = (HttpDelete)createMethod("delete", uri); dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); final HttpResponse response = executeMethod(dm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to delete object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); } dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); } protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { HttpResponse response = null; try { response = _client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); response = _client.execute(method); } } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Brocade Switch", e); method.releaseConnection(); throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); } return response; } private String responseToErrorMessage(HttpResponse response) throws IOException { if ("text/html".equals(response.getEntity().getContentType().getValue())) { try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } } return null; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14767 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java/#L63-L542 | 1 | 2537 | 14767 | major |
| 2623 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 15063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 2623 | 15063 | minor |
| 478 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 4622 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 478 | 4622 | minor |
| 1253 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | blob | t | t | f | blob | data class | 0 | 10456 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 1253 | 10456 | minor |
| 3876 | YES I found bad smells The bad smells are: 1.Null check, 2.Long method, 3.Magic number, 4.Incomplete conditional logic, 5.Misleading comment | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | Null check, 2Long method, 3Magic number, 4Incomplete conditional logic, 5Misleading comment | t | f | f | .Null check, 2.Long method, 3.Magic number, 4.Incomplete conditional logic, 5.Misleading comment | feature envy | 0 | 10126 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 3876 | 10126 | major |
| 1730 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11819 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 2 | 1730 | 11819 | major |
| 1883 | { "message": "YES I found bad smells", "bad smells are": [ "6. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | 6. long method | t | t | f | 6. long method | feature envy | 0 | 12289 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 1883 | 12289 | minor |
| 1533 | {"message":"YES I found bad smells","bad smells":["Long Method","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GenericsUtils { public static final GenericsType[] EMPTY_GENERICS_ARRAY = GenericsType.EMPTY_ARRAY; public static final String JAVA_LANG_OBJECT = "java.lang.Object"; /** * Given a parameterized type and a generic type information, aligns actual type parameters. For example, if a * class uses generic type <T,U,V> (redirectGenericTypes), is used with actual type parameters * <java.lang.String, U,V>, then a class or interface using generic types <T,V> * will be aligned to <java.lang.String,V> * * @param redirectGenericTypes the type arguments or the redirect class node * @param parameterizedTypes the actual type arguments used on this class node * @param alignmentTarget the generic type arguments to which we want to align to * @return aligned type arguments * @deprecated You shouldn't call this method because it is inherently unreliable */ @Deprecated public static GenericsType[] alignGenericTypes(final GenericsType[] redirectGenericTypes, final GenericsType[] parameterizedTypes, final GenericsType[] alignmentTarget) { if (alignmentTarget == null) return EMPTY_GENERICS_ARRAY; if (parameterizedTypes == null || parameterizedTypes.length == 0) return alignmentTarget; GenericsType[] generics = new GenericsType[alignmentTarget.length]; for (int i = 0, scgtLength = alignmentTarget.length; i < scgtLength; i++) { final GenericsType currentTarget = alignmentTarget[i]; GenericsType match = null; if (redirectGenericTypes != null) { for (int j = 0; j < redirectGenericTypes.length && match == null; j++) { GenericsType redirectGenericType = redirectGenericTypes[j]; if (redirectGenericType.isCompatibleWith(currentTarget.getType())) { if (currentTarget.isPlaceholder() && redirectGenericType.isPlaceholder() && !currentTarget.getName().equals(redirectGenericType.getName())) { // check if there's a potential better match boolean skip = false; for (int k = j + 1; k < redirectGenericTypes.length && !skip; k++) { GenericsType ogt = redirectGenericTypes[k]; if (ogt.isPlaceholder() && ogt.isCompatibleWith(currentTarget.getType()) && ogt.getName().equals(currentTarget.getName())) { skip = true; } } if (skip) continue; } match = parameterizedTypes[j]; if (currentTarget.isWildcard()) { // if alignment target is a wildcard type // then we must make best effort to return a parameterized // wildcard ClassNode lower = currentTarget.getLowerBound() != null ? match.getType() : null; ClassNode[] currentUpper = currentTarget.getUpperBounds(); ClassNode[] upper = currentUpper != null ? new ClassNode[currentUpper.length] : null; if (upper != null) { for (int k = 0; k < upper.length; k++) { upper[k] = currentUpper[k].isGenericsPlaceHolder() ? match.getType() : currentUpper[k]; } } match = new GenericsType(ClassHelper.makeWithoutCaching("?"), upper, lower); match.setWildcard(true); } } } } if (match == null) { match = currentTarget; } generics[i] = match; } return generics; } /** * Generates a wildcard generic type in order to be used for checks against class nodes. * See {@link GenericsType#isCompatibleWith(org.codehaus.groovy.ast.ClassNode)}. * * @param types the type to be used as the wildcard upper bound * @return a wildcard generics type */ public static GenericsType buildWildcardType(final ClassNode... types) { ClassNode base = ClassHelper.makeWithoutCaching("?"); GenericsType gt = new GenericsType(base, types, null); gt.setWildcard(true); return gt; } public static Map extractPlaceholders(ClassNode cn) { Map ret = new HashMap(); extractPlaceholders(cn, ret); return ret; } /** * For a given classnode, fills in the supplied map with the parameterized * types it defines. * * @param node the class node to check * @param map the generics type information collector */ public static void extractPlaceholders(ClassNode node, Map map) { if (node == null) return; if (node.isArray()) { extractPlaceholders(node.getComponentType(), map); return; } if (!node.isUsingGenerics() || !node.isRedirectNode()) return; GenericsType[] parameterized = node.getGenericsTypes(); if (parameterized == null || parameterized.length == 0) return; GenericsType[] redirectGenericsTypes = node.redirect().getGenericsTypes(); if (redirectGenericsTypes == null || (node.isGenericsPlaceHolder() && redirectGenericsTypes.length != parameterized.length) /* GROOVY-8609 */ ) { redirectGenericsTypes = parameterized; } if (redirectGenericsTypes.length != parameterized.length) { throw new GroovyBugError("Expected earlier checking to detect generics parameter arity mismatch" + "\nExpected: " + node.getName() + toGenericTypesString(redirectGenericsTypes) + "\nSupplied: " + node.getName() + toGenericTypesString(parameterized)); } List valueList = new LinkedList<>(); for (int i = 0; i < redirectGenericsTypes.length; i++) { GenericsType redirectType = redirectGenericsTypes[i]; if (redirectType.isPlaceholder()) { GenericsTypeName name = new GenericsTypeName(redirectType.getName()); if (!map.containsKey(name)) { GenericsType value = parameterized[i]; map.put(name, value); valueList.add(value); } } } for (GenericsType value : valueList) { if (value.isWildcard()) { ClassNode lowerBound = value.getLowerBound(); if (lowerBound != null) { extractPlaceholders(lowerBound, map); } ClassNode[] upperBounds = value.getUpperBounds(); if (upperBounds != null) { for (ClassNode upperBound : upperBounds) { extractPlaceholders(upperBound, map); } } } else if (!value.isPlaceholder()) { extractPlaceholders(value.getType(), map); } } } public static String toGenericTypesString(GenericsType[] genericsTypes) { if (genericsTypes == null) return ""; StringBuilder sb = new StringBuilder("<"); for (int i = 0, n = genericsTypes.length; i < n; i++) { sb.append(genericsTypes[i].toString()); if (i < n - 1) { sb.append(","); } } sb.append("> "); return sb.toString(); } /** * Interface class nodes retrieved from {@link org.codehaus.groovy.ast.ClassNode#getInterfaces()} * or {@link org.codehaus.groovy.ast.ClassNode#getAllInterfaces()} are returned with generic type * arguments. This method allows returning a parameterized interface given the parameterized class * node which implements this interface. * * @param hint the class node where generics types are parameterized * @param target the interface we want to parameterize generics types * @return a parameterized interface class node * @deprecated Use #parameterizeType instead */ @Deprecated public static ClassNode parameterizeInterfaceGenerics(final ClassNode hint, final ClassNode target) { return parameterizeType(hint, target); } /** * Interface class nodes retrieved from {@link org.codehaus.groovy.ast.ClassNode#getInterfaces()} * or {@link org.codehaus.groovy.ast.ClassNode#getAllInterfaces()} are returned with generic type * arguments. This method allows returning a parameterized interface given the parameterized class * node which implements this interface. * * @param hint the class node where generics types are parameterized * @param target the interface we want to parameterize generics types * @return a parameterized interface class node */ public static ClassNode parameterizeType(final ClassNode hint, final ClassNode target) { if (hint.isArray()) { if (target.isArray()) { return parameterizeType(hint.getComponentType(), target.getComponentType()).makeArray(); } return target; } if (!target.equals(hint) && implementsInterfaceOrIsSubclassOf(target, hint)) { ClassNode nextSuperClass = ClassHelper.getNextSuperClass(target, hint); if (!hint.equals(nextSuperClass)) { Map genericsSpec = createGenericsSpec(hint); extractSuperClassGenerics(hint, nextSuperClass, genericsSpec); ClassNode result = correctToGenericsSpecRecurse(genericsSpec, nextSuperClass); return parameterizeType(result, target); } } Map genericsSpec = createGenericsSpec(hint); ClassNode targetRedirect = target.redirect(); genericsSpec = createGenericsSpec(targetRedirect, genericsSpec); extractSuperClassGenerics(hint, targetRedirect, genericsSpec); return correctToGenericsSpecRecurse(genericsSpec, targetRedirect); } public static ClassNode nonGeneric(ClassNode type) { if (type.isUsingGenerics()) { final ClassNode nonGen = ClassHelper.makeWithoutCaching(type.getName()); nonGen.setRedirect(type); nonGen.setGenericsTypes(null); nonGen.setUsingGenerics(false); return nonGen; } if (type.isArray() && type.getComponentType().isUsingGenerics()) { return type.getComponentType().getPlainNodeReference().makeArray(); } return type; } public static ClassNode newClass(ClassNode type) { return type.getPlainNodeReference(); } public static ClassNode makeClassSafe(Class klass) { return makeClassSafeWithGenerics(ClassHelper.make(klass)); } public static ClassNode makeClassSafeWithGenerics(Class klass, ClassNode genericsType) { GenericsType[] genericsTypes = new GenericsType[1]; genericsTypes[0] = new GenericsType(genericsType); return makeClassSafeWithGenerics(ClassHelper.make(klass), genericsTypes); } public static ClassNode makeClassSafe0(ClassNode type, GenericsType... genericTypes) { ClassNode plainNodeReference = newClass(type); if (genericTypes != null && genericTypes.length > 0) { plainNodeReference.setGenericsTypes(genericTypes); if (type.isGenericsPlaceHolder()) plainNodeReference.setGenericsPlaceHolder(true); } return plainNodeReference; } public static ClassNode makeClassSafeWithGenerics(ClassNode type, GenericsType... genericTypes) { if (type.isArray()) { return makeClassSafeWithGenerics(type.getComponentType(), genericTypes).makeArray(); } GenericsType[] gtypes = GenericsType.EMPTY_ARRAY; if (genericTypes != null) { gtypes = new GenericsType[genericTypes.length]; System.arraycopy(genericTypes, 0, gtypes, 0, gtypes.length); } return makeClassSafe0(type, gtypes); } public static MethodNode correctToGenericsSpec(Map genericsSpec, MethodNode mn) { ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType()); Parameter[] origParameters = mn.getParameters(); Parameter[] newParameters = new Parameter[origParameters.length]; for (int i = 0; i < origParameters.length; i++) { Parameter origParameter = origParameters[i]; newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression()); } return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode()); } public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type) { return correctToGenericsSpecRecurse(genericsSpec, type, new ArrayList()); } /** * @since 2.4.1 */ public static ClassNode[] correctToGenericsSpecRecurse(Map genericsSpec, ClassNode[] types) { if (types == null || types.length == 1) return types; ClassNode[] newTypes = new ClassNode[types.length]; boolean modified = false; for (int i = 0; i < types.length; i++) { newTypes[i] = correctToGenericsSpecRecurse(genericsSpec, types[i], new ArrayList()); modified = modified || (types[i] != newTypes[i]); } if (!modified) return types; return newTypes; } public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type, List exclusions) { if (type.isArray()) { return correctToGenericsSpecRecurse(genericsSpec, type.getComponentType(), exclusions).makeArray(); } if (type.isGenericsPlaceHolder() && !exclusions.contains(type.getUnresolvedName())) { String name = type.getGenericsTypes()[0].getName(); type = genericsSpec.get(name); if (type != null && type.isGenericsPlaceHolder() && type.getGenericsTypes() == null) { ClassNode placeholder = ClassHelper.makeWithoutCaching(type.getUnresolvedName()); placeholder.setGenericsPlaceHolder(true); type = makeClassSafeWithGenerics(type, new GenericsType(placeholder)); } } if (type == null) type = ClassHelper.OBJECT_TYPE; GenericsType[] oldgTypes = type.getGenericsTypes(); GenericsType[] newgTypes = GenericsType.EMPTY_ARRAY; if (oldgTypes != null) { newgTypes = new GenericsType[oldgTypes.length]; for (int i = 0; i < newgTypes.length; i++) { GenericsType oldgType = oldgTypes[i]; if (oldgType.isPlaceholder()) { if (genericsSpec.get(oldgType.getName()) != null) { newgTypes[i] = new GenericsType(genericsSpec.get(oldgType.getName())); } else { newgTypes[i] = new GenericsType(ClassHelper.OBJECT_TYPE); } } else if (oldgType.isWildcard()) { ClassNode oldLower = oldgType.getLowerBound(); ClassNode lower = oldLower != null ? correctToGenericsSpecRecurse(genericsSpec, oldLower, exclusions) : null; ClassNode[] oldUpper = oldgType.getUpperBounds(); ClassNode[] upper = null; if (oldUpper != null) { upper = new ClassNode[oldUpper.length]; for (int j = 0; j < oldUpper.length; j++) { upper[j] = correctToGenericsSpecRecurse(genericsSpec, oldUpper[j], exclusions); } } GenericsType fixed = new GenericsType(oldgType.getType(), upper, lower); fixed.setName(oldgType.getName()); fixed.setWildcard(true); newgTypes[i] = fixed; } else { newgTypes[i] = new GenericsType(correctToGenericsSpecRecurse(genericsSpec, correctToGenericsSpec(genericsSpec, oldgType), exclusions)); } } } return makeClassSafeWithGenerics(type, newgTypes); } public static ClassNode correctToGenericsSpec(Map genericsSpec, GenericsType type) { ClassNode ret = null; if (type.isPlaceholder()) { String name = type.getName(); ret = genericsSpec.get(name); } if (ret == null) ret = type.getType(); return ret; } public static ClassNode correctToGenericsSpec(Map genericsSpec, ClassNode type) { if (type.isArray()) { return correctToGenericsSpec(genericsSpec, type.getComponentType()).makeArray(); } if (type.isGenericsPlaceHolder()) { String name = type.getGenericsTypes()[0].getName(); type = genericsSpec.get(name); } if (type == null) type = ClassHelper.OBJECT_TYPE; return type; } @SuppressWarnings("unchecked") public static Map createGenericsSpec(ClassNode current) { return createGenericsSpec(current, Collections.EMPTY_MAP); } public static Map createGenericsSpec(ClassNode current, Map oldSpec) { Map ret = new HashMap(oldSpec); // ret contains the type specs, what we now need is the type spec for the // current class. To get that we first apply the type parameters to the // current class and then use the type names of the current class to reset // the map. Example: // class A{} // class B extends A {} // first we have: T->Number // we apply it to A -> A // resulting in: V->Number,W->Long,X->String GenericsType[] sgts = current.getGenericsTypes(); if (sgts != null) { ClassNode[] spec = new ClassNode[sgts.length]; for (int i = 0; i < spec.length; i++) { spec[i] = correctToGenericsSpec(ret, sgts[i]); } GenericsType[] newGts = current.redirect().getGenericsTypes(); if (newGts == null) return ret; ret.clear(); for (int i = 0; i < spec.length; i++) { ret.put(newGts[i].getName(), spec[i]); } } return ret; } public static Map addMethodGenerics(MethodNode current, Map oldSpec) { Map ret = new HashMap(oldSpec); // ret starts with the original type specs, now add gts for the current method if any GenericsType[] sgts = current.getGenericsTypes(); if (sgts != null) { for (GenericsType sgt : sgts) { String name = sgt.getName(); if (sgt.isPlaceholder()) { ClassNode redirect; if (sgt.getUpperBounds() != null) { redirect = sgt.getUpperBounds()[0]; } else if (sgt.getLowerBound() != null) { redirect = sgt.getLowerBound(); } else { redirect = ClassHelper.OBJECT_TYPE; } ClassNode type = ClassHelper.makeWithoutCaching(name); type.setGenericsPlaceHolder(true); type.setRedirect(redirect); ret.put(name, type); } else { ret.put(name, sgt.getType()); } } } return ret; } public static void extractSuperClassGenerics(ClassNode type, ClassNode target, Map spec) { // TODO: this method is very similar to StaticTypesCheckingSupport#extractGenericsConnections, // but operates on ClassNodes instead of GenericsType if (target == null || type == target) return; if (type.isArray() && target.isArray()) { extractSuperClassGenerics(type.getComponentType(), target.getComponentType(), spec); } else if (type.isArray() && JAVA_LANG_OBJECT.equals(target.getName())) { // Object is superclass of arrays but no generics involved } else if (target.isGenericsPlaceHolder() || type.equals(target) || !implementsInterfaceOrIsSubclassOf(type, target)) { // structural match route if (target.isGenericsPlaceHolder()) { spec.put(target.getGenericsTypes()[0].getName(), type); } else { extractSuperClassGenerics(type.getGenericsTypes(), target.getGenericsTypes(), spec); } } else { // have first to find matching super class or interface ClassNode superClass = getSuperClass(type, target); if (superClass != null) { ClassNode corrected = getCorrectedClassNode(type, superClass, false); extractSuperClassGenerics(corrected, target, spec); } else { // if we reach here, we have an unhandled case throw new GroovyBugError("The type " + type + " seems not to normally extend " + target + ". Sorry, I cannot handle this."); } } } public static ClassNode getSuperClass(ClassNode type, ClassNode target) { ClassNode superClass = ClassHelper.getNextSuperClass(type, target); if (superClass == null) { if (ClassHelper.isPrimitiveType(type)) { superClass = ClassHelper.getNextSuperClass(ClassHelper.getWrapper(type), target); } } return superClass; } private static void extractSuperClassGenerics(GenericsType[] usage, GenericsType[] declaration, Map spec) { // if declaration does not provide generics, there is no connection to make if (usage == null || declaration == null || declaration.length == 0) return; if (usage.length != declaration.length) return; // both have generics for (int i = 0; i < usage.length; i++) { GenericsType ui = usage[i]; GenericsType di = declaration[i]; if (di.isPlaceholder()) { spec.put(di.getName(), ui.getType()); } else if (di.isWildcard()) { if (ui.isWildcard()) { extractSuperClassGenerics(ui.getLowerBound(), di.getLowerBound(), spec); extractSuperClassGenerics(ui.getUpperBounds(), di.getUpperBounds(), spec); } else { ClassNode cu = ui.getType(); extractSuperClassGenerics(cu, di.getLowerBound(), spec); ClassNode[] upperBounds = di.getUpperBounds(); if (upperBounds != null) { for (ClassNode cn : upperBounds) { extractSuperClassGenerics(cu, cn, spec); } } } } else { extractSuperClassGenerics(ui.getType(), di.getType(), spec); } } } private static void extractSuperClassGenerics(ClassNode[] usage, ClassNode[] declaration, Map spec) { if (usage == null || declaration == null || declaration.length == 0) return; // both have generics for (int i = 0; i < usage.length; i++) { ClassNode ui = usage[i]; ClassNode di = declaration[i]; if (di.isGenericsPlaceHolder()) { spec.put(di.getGenericsTypes()[0].getName(), di); } else if (di.isUsingGenerics()) { extractSuperClassGenerics(ui.getGenericsTypes(), di.getGenericsTypes(), spec); } } } public static ClassNode[] parseClassNodesFromString( final String option, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage) { GroovyLexer lexer = new GroovyLexer(new StringReader("DummyNode<" + option + ">")); final GroovyRecognizer rn = GroovyRecognizer.make(lexer); try { rn.classOrInterfaceType(true); final AtomicReference ref = new AtomicReference(); AntlrParserPlugin plugin = new AntlrParserPlugin() { @Override public ModuleNode buildAST(final SourceUnit sourceUnit, final ClassLoader classLoader, final Reduction cst) throws ParserException { ref.set(makeTypeWithArguments(rn.getAST())); return null; } }; plugin.buildAST(null, null, null); ClassNode parsedNode = ref.get(); // the returned node is DummyNode genericsSpec, GenericsType[] oldPlaceHolders) { if (oldPlaceHolders == null || oldPlaceHolders.length == 0) return oldPlaceHolders; if (genericsSpec.isEmpty()) return oldPlaceHolders; GenericsType[] newTypes = new GenericsType[oldPlaceHolders.length]; for (int i = 0; i < oldPlaceHolders.length; i++) { GenericsType old = oldPlaceHolders[i]; if (!old.isPlaceholder()) throw new GroovyBugError("Given generics type " + old + " must be a placeholder!"); ClassNode fromSpec = genericsSpec.get(old.getName()); if (fromSpec != null) { if (fromSpec.isGenericsPlaceHolder()) { ClassNode[] upper = new ClassNode[]{fromSpec.redirect()}; newTypes[i] = new GenericsType(fromSpec, upper, null); } else { newTypes[i] = new GenericsType(fromSpec); } } else { ClassNode[] upper = old.getUpperBounds(); ClassNode[] newUpper = upper; if (upper != null && upper.length > 0) { ClassNode[] upperCorrected = new ClassNode[upper.length]; for (int j = 0; j < upper.length; j++) { upperCorrected[i] = correctToGenericsSpecRecurse(genericsSpec, upper[j]); } upper = upperCorrected; } ClassNode lower = old.getLowerBound(); ClassNode newLower = correctToGenericsSpecRecurse(genericsSpec, lower); if (lower == newLower && upper == newUpper) { newTypes[i] = oldPlaceHolders[i]; } else { ClassNode newPlaceHolder = ClassHelper.make(old.getName()); GenericsType gt = new GenericsType(newPlaceHolder, newUpper, newLower); gt.setPlaceholder(true); newTypes[i] = gt; } } } return newTypes; } private static final String TRUE_STR = "true"; private static final boolean PARAMETERIZED_TYPE_CACHE_ENABLED = TRUE_STR.equals(SystemUtil.getSystemPropertySafe("groovy.enable.parameterized.type.cache", TRUE_STR)); /** * Try to get the parameterized type from the cache. * If no cached item found, cache and return the result of {@link #findParameterizedType(ClassNode, ClassNode, boolean)} */ public static ClassNode findParameterizedTypeFromCache(final ClassNode genericsClass, final ClassNode actualType, boolean tryToFindExactType) { if (!PARAMETERIZED_TYPE_CACHE_ENABLED) { return findParameterizedType(genericsClass, actualType, tryToFindExactType); } SoftReference sr = PARAMETERIZED_TYPE_CACHE.getAndPut(new ParameterizedTypeCacheKey(genericsClass, actualType), key -> new SoftReference<>(findParameterizedType(key.getGenericsClass(), key.getActualType(), tryToFindExactType))); return null == sr ? null : sr.get(); } /** * Get the parameterized type by search the whole class hierarchy according to generics class and actual receiver. * {@link #findParameterizedTypeFromCache(ClassNode, ClassNode, boolean)} is strongly recommended for better performance. * * @param genericsClass the generics class * @param actualType the actual type * @param tryToFindExactType whether to try to find exact type * @return the parameterized type */ public static ClassNode findParameterizedType(ClassNode genericsClass, ClassNode actualType, boolean tryToFindExactType) { ClassNode parameterizedType = null; if (null == genericsClass.getGenericsTypes()) { return parameterizedType; } GenericsType[] declaringGenericsTypes = genericsClass.getGenericsTypes(); List classNodeList = new LinkedList<>(getAllSuperClassesAndInterfaces(actualType)); classNodeList.add(0, actualType); LinkedList parameterizedTypeCandidateList = new LinkedList<>(); for (ClassNode cn : classNodeList) { if (cn == genericsClass) { continue; } if (tryToFindExactType && null != cn.getGenericsTypes() && hasNonPlaceHolders(cn)) { parameterizedTypeCandidateList.add(cn); } if (!(genericsClass.equals(cn.redirect()))) { continue; } if (isGenericsTypeArraysLengthEqual(declaringGenericsTypes, cn.getGenericsTypes())) { parameterizedType = cn; break; } } if (null == parameterizedType) { if (!parameterizedTypeCandidateList.isEmpty()) { parameterizedType = parameterizedTypeCandidateList.getLast(); } } return parameterizedType; } private static boolean isGenericsTypeArraysLengthEqual(GenericsType[] declaringGenericsTypes, GenericsType[] actualGenericsTypes) { return null != actualGenericsTypes && declaringGenericsTypes.length == actualGenericsTypes.length; } private static List getAllSuperClassesAndInterfaces(ClassNode actualReceiver) { List superClassAndInterfaceList = new LinkedList<>(); List allSuperClassNodeList = getAllUnresolvedSuperClasses(actualReceiver); superClassAndInterfaceList.addAll(allSuperClassNodeList); superClassAndInterfaceList.addAll(actualReceiver.getAllInterfaces()); for (ClassNode superClassNode : allSuperClassNodeList) { superClassAndInterfaceList.addAll(superClassNode.getAllInterfaces()); } return superClassAndInterfaceList; } private static List getAllUnresolvedSuperClasses(ClassNode actualReceiver) { List superClassNodeList = new LinkedList<>(); for (ClassNode cn = actualReceiver.getUnresolvedSuperClass(); null != cn && ClassHelper.OBJECT_TYPE != cn; cn = cn.getUnresolvedSuperClass()) { superClassNodeList.add(cn); } return superClassNodeList; } private static final EvictableCache> PARAMETERIZED_TYPE_CACHE = new ConcurrentSoftCache<>(64); /** * Clear the parameterized type cache * It is useful to IDE as the type being compiled are continuously being edited/altered, see GROOVY-8675 */ public static void clearParameterizedTypeCache() { PARAMETERIZED_TYPE_CACHE.clearAll(); } /** * map declaring generics type to actual generics type, e.g. GROOVY-7204: * declaring generics types: T, S extends Serializable * actual generics types : String, Long * * the result map is [ * T: String, * S: Long * ] * * The resolved types can not help us to choose methods correctly if the argument is a string: T: Object, S: Serializable * so we need actual types: T: String, S: Long */ public static Map makeDeclaringAndActualGenericsTypeMap(ClassNode declaringClass, ClassNode actualReceiver) { return doMakeDeclaringAndActualGenericsTypeMap(declaringClass, actualReceiver, false).getV1(); } /** * The method is similar with {@link GenericsUtils#makeDeclaringAndActualGenericsTypeMap(ClassNode, ClassNode)}, * The main difference is that the method will try to map all placeholders found to the relevant exact types, * but the other will not try even if the parameterized type has placeholders * * @param declaringClass the generics class node declaring the generics types * @param actualReceiver the sub-class class node * @return the placeholder-to-actualtype mapping * @since 3.0.0 */ public static Map makeDeclaringAndActualGenericsTypeMapOfExactType(ClassNode declaringClass, ClassNode actualReceiver) { List parameterizedTypeList = new LinkedList<>(); Map result = makeDeclaringAndActualGenericsTypeMapOfExactType(declaringClass, actualReceiver, parameterizedTypeList); return connectGenericsTypes(result); } private static Map makeDeclaringAndActualGenericsTypeMapOfExactType(ClassNode declaringClass, ClassNode actualReceiver, List parameterizedTypeList) { Tuple2, ClassNode> resultAndParameterizedTypeTuple = doMakeDeclaringAndActualGenericsTypeMap(declaringClass, actualReceiver, true); ClassNode parameterizedType = resultAndParameterizedTypeTuple.getV2(); Map result = resultAndParameterizedTypeTuple.getV1(); if (hasPlaceHolders(parameterizedType) && !parameterizedTypeList.contains(parameterizedType)) { parameterizedTypeList.add(parameterizedType); result.putAll(makeDeclaringAndActualGenericsTypeMapOfExactType(parameterizedType, actualReceiver, parameterizedTypeList)); } return connectGenericsTypes(result); } private static Tuple2, ClassNode> doMakeDeclaringAndActualGenericsTypeMap(ClassNode declaringClass, ClassNode actualReceiver, boolean tryToFindExactType) { ClassNode parameterizedType = findParameterizedTypeFromCache(declaringClass, actualReceiver, tryToFindExactType); if (null == parameterizedType) { return tuple(Collections.emptyMap(), parameterizedType); } Map result = new LinkedHashMap<>(); result.putAll(makePlaceholderAndParameterizedTypeMap(declaringClass)); result.putAll(makePlaceholderAndParameterizedTypeMap(parameterizedType)); result = connectGenericsTypes(result); return tuple(result, parameterizedType); } private static Map makePlaceholderAndParameterizedTypeMap(ClassNode declaringClass) { if (null == declaringClass) { return Collections.emptyMap(); } Map result = new LinkedHashMap<>(); ClassNode redirectDeclaringClass = declaringClass.redirect(); GenericsType[] declaringGenericsTypes = declaringClass.getGenericsTypes(); GenericsType[] redirectDeclaringGenericsTypes = redirectDeclaringClass.getGenericsTypes(); if (null != declaringGenericsTypes && null != redirectDeclaringGenericsTypes) { for (int i = 0, n = declaringGenericsTypes.length; i < n; i++) { result.put(redirectDeclaringGenericsTypes[i], declaringGenericsTypes[i]); } } return result; } private static Map connectGenericsTypes(Map genericsTypeMap) { Map result = new LinkedHashMap<>(); outter: for (Map.Entry entry : genericsTypeMap.entrySet()) { GenericsType key = entry.getKey(); GenericsType value = entry.getValue(); if (value.isPlaceholder()) { for (Map.Entry genericsTypeMapEntry : genericsTypeMap.entrySet()) { GenericsType genericsTypeMapEntryValue = genericsTypeMapEntry.getValue(); if (!genericsTypeMapEntryValue.isPlaceholder() && (genericsTypeMapEntry.getKey().getName().equals(value.getName()))) { result.put(key, genericsTypeMapEntryValue); // connected to actual type continue outter; } } } result.put(key, value); } return result; } /** * Check whether the ClassNode has non generics placeholders, aka not placeholder * * @param parameterizedType the class node * @return the result * @since 3.0.0 */ public static boolean hasNonPlaceHolders(ClassNode parameterizedType) { return checkPlaceHolders(parameterizedType, genericsType -> !genericsType.isPlaceholder()); } /** * Check whether the ClassNode has generics placeholders * @param parameterizedType the class node * @return the result * @since 3.0.0 */ public static boolean hasPlaceHolders(ClassNode parameterizedType) { return checkPlaceHolders(parameterizedType, genericsType -> genericsType.isPlaceholder()); } private static boolean checkPlaceHolders(ClassNode parameterizedType, Predicate p) { if (null == parameterizedType) return false; GenericsType[] genericsTypes = parameterizedType.getGenericsTypes(); if (null == genericsTypes) return false; for (GenericsType genericsType : genericsTypes) { if (p.test(genericsType)) { return true; } } return false; } /** * Get the parameter and return types of the abstract method of SAM * * If the abstract method is not parameterized, we will get generics placeholders, e.g. T, U * For example, the abstract method of {@link java.util.function.Function} is * * R apply(T t); * * * We parameterize the above interface as {@code Function}, then the abstract method will be * * Integer apply(String t); * * * When we call {@code parameterizeSAM} on the ClassNode {@code Function}, * we can get parameter types and return type of the above abstract method, * i.e. ClassNode {@code ClassHelper.STRING_TYPE} and {@code ClassHelper.Integer_TYPE} * * @param sam the class node which contains only one abstract method * @return the parameter and return types * @since 3.0.0 * */ public static Tuple2 parameterizeSAM(ClassNode sam) { MethodNode methodNode = ClassHelper.findSAM(sam); final Map map = makeDeclaringAndActualGenericsTypeMapOfExactType(methodNode.getDeclaringClass(), sam); ClassNode[] parameterTypes = Arrays.stream(methodNode.getParameters()) .map(e -> { ClassNode originalParameterType = e.getType(); return originalParameterType.isGenericsPlaceHolder() ? findActualTypeByGenericsPlaceholderName(originalParameterType.getUnresolvedName(), map) : originalParameterType; }) .toArray(ClassNode[]::new); ClassNode originalReturnType = methodNode.getReturnType(); ClassNode returnType = originalReturnType.isGenericsPlaceHolder() ? findActualTypeByGenericsPlaceholderName(originalReturnType.getUnresolvedName(), map) : originalReturnType; return tuple(parameterTypes, returnType); } /** * Get the actual type according to the placeholder name * * @param placeholderName the placeholder name, e.g. T, E * @param genericsPlaceholderAndTypeMap the result of {@link #makeDeclaringAndActualGenericsTypeMap(ClassNode, ClassNode)} * @return the actual type */ public static ClassNode findActualTypeByGenericsPlaceholderName(String placeholderName, Map genericsPlaceholderAndTypeMap) { for (Map.Entry entry : genericsPlaceholderAndTypeMap.entrySet()) { GenericsType declaringGenericsType = entry.getKey(); if (placeholderName.equals(declaringGenericsType.getName())) { return entry.getValue().getType().redirect(); } } return null; } private static class ParameterizedTypeCacheKey { private ClassNode genericsClass; private ClassNode actualType; public ParameterizedTypeCacheKey(ClassNode genericsClass, ClassNode actualType) { this.genericsClass = genericsClass; this.actualType = actualType; } public ClassNode getGenericsClass() { return genericsClass; } public void setGenericsClass(ClassNode genericsClass) { this.genericsClass = genericsClass; } public ClassNode getActualType() { return actualType; } public void setActualType(ClassNode actualType) { this.actualType = actualType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParameterizedTypeCacheKey cacheKey = (ParameterizedTypeCacheKey) o; return genericsClass == cacheKey.genericsClass && actualType == cacheKey.actualType; } @Override public int hashCode() { return Objects.hash(genericsClass, actualType); } } } |
blob | long method, long method | t | t | f | long method, long method | blob | 0 | 11210 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java/#L68-L1044 | 1 | 1533 | 11210 | critical |
| 2179 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 13412 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 2179 | 13412 | minor |
| 3728 | {"result":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 9201 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 1 | 3728 | 9201 | minor |
| 110 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class PushCommand extends KeyCommand { private List values; private boolean upsert; private Direction direction; private PushCommand(@Nullable ByteBuffer key, List values, Direction direction, boolean upsert) { super(key); this.values = values; this.upsert = upsert; this.direction = direction; } /** * Creates a new {@link PushCommand} for right push ({@literal RPUSH}). * * @return a new {@link PushCommand} for right push ({@literal RPUSH}). */ public static PushCommand right() { return new PushCommand(null, Collections.emptyList(), Direction.RIGHT, true); } /** * Creates a new {@link PushCommand} for left push ({@literal LPUSH}). * * @return a new {@link PushCommand} for left push ({@literal LPUSH}). */ public static PushCommand left() { return new PushCommand(null, Collections.emptyList(), Direction.LEFT, true); } /** * Applies the {@literal value}. Constructs a new command instance with all previously configured properties. * * @param value must not be {@literal null}. * @return a new {@link PushCommand} with {@literal value} applied. */ public PushCommand value(ByteBuffer value) { Assert.notNull(value, "Value must not be null!"); return new PushCommand(null, Collections.singletonList(value), direction, upsert); } /** * Applies a {@link List} of {@literal values}. * * @param values must not be {@literal null}. * @return a new {@link PushCommand} with {@literal values} applied. */ public PushCommand values(List values) { Assert.notNull(values, "Values must not be null!"); return new PushCommand(null, new ArrayList<>(values), direction, upsert); } /** * Applies the {@literal key}. Constructs a new command instance with all previously configured properties. * * @param key must not be {@literal null}. * @return a new {@link PushCommand} with {@literal key} applied. */ public PushCommand to(ByteBuffer key) { Assert.notNull(key, "Key must not be null!"); return new PushCommand(key, values, direction, upsert); } /** * Disable upsert. Constructs a new command instance with all previously configured properties. * * @return a new {@link PushCommand} with upsert disabled. */ public PushCommand ifExists() { return new PushCommand(getKey(), values, direction, false); } /** * @return never {@literal null}. */ public List getValues() { return values; } /** * @return */ public boolean getUpsert() { return upsert; } /** * @return never {@literal null}. */ public Direction getDirection() { return direction; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1459 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/ReactiveListCommands.java/#L63-L164 | 2 | 110 | 1459 | major |
| 1403 | YES I found bad smells the bad smells are: 1. Inconsistent formatting and indentation. 2. Use of SuppressWarnings annotation, indicating a potential problem that is being ignored. 3. Use of a raw type in the Map declaration. 4. Unnecessary interface declaration within an interface. 5. Confusing and lengthy naming conventions, with multiple references to the same variables or properties. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | Inconsistent formatting and indentation2 Use of SuppressWarnings annotation, indicating a potential problem that is being ignored3 Use of a raw type in the Map declaration4 Unnecessary interface declaration within an interface5 Confusing and lengthy naming conventions, with multiple references to the same variables or properties | t | f | f | . Inconsistent formatting and indentation.2. Use of SuppressWarnings annotation, indicating a potential problem that is being ignored.3. Use of a raw type in the Map declaration.4. Unnecessary interface declaration within an interface.5. Confusing and lengthy naming conventions, with multiple references to the same variables or properties. | data class | 0 | 10864 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 2 | 1403 | 10864 | major |
| 530 | YES I found bad smells the bad smells are: Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains | t | f | f | Long method, Feature envy, Inappropriate intimacy, Inconsistent naming, Duplicate code, Lazy class, Inconsistent formatting, Commented code, Message chains. | data class | 0 | 5476 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 530 | 5476 | minor |
| 2965 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Lack of cohesion 4. Redundant code (e.g. the constructor and get methods for validBits and value) 5. No use of encapsulation (all fields are public) 6. Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods) 7. Code duplication (the code for encoding and decoding is repeated in the inner Codec class) 8. Poor naming conventions (e.g. getType() method in the Codec class could be named more descriptively) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | Long method2 Feature envy3 Lack of cohesion4 Redundant code (eg the constructor and get methods for validBits and value)5 No use of encapsulation (all fields are public)6 Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods)7 Code duplication (the code for encoding and decoding is repeated in the inner Codec class)8 Poor naming conventions (eg getType() method in the Codec class could be named more descriptively) | t | f | f | . Long method2. Feature envy3. Lack of cohesion4. Redundant code (e.g. the constructor and get methods for validBits and value)5. No use of encapsulation (all fields are public)6. Violation of single responsibility principle (the OptionSet class has both encoding and decoding methods)7. Code duplication (the code for encoding and decoding is repeated in the inner Codec class)8. Poor naming conventions (e.g. getType() method in the Codec class could be named more descriptively) | data class | 0 | 2728 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 2 | 2965 | 2728 | minor |
| 5770 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14810 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5770 | 14810 | major |
| 245 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code", "Data class", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
blob | long method, duplicate code, data class, feature envy | t | t | f | long method, duplicate code, data class, feature envy | blob | 0 | 2653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 2 | 245 | 2653 | minor |
| 6 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
feature envy | long method, duplicate code | t | t | f | long method, duplicate code | feature envy | 0 | 570 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 2 | 6 | 570 | minor |
| 1209 | YES I found bad smells the bad smells are: 1. Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code. 2. Long constructor - the class contains a long constructor which can be refactored into smaller methods. 3. Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code2 Long constructor - the class contains a long constructor which can be refactored into smaller methods3 Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class | t | f | f | . Too many comments - the code has a lot of comments that could potentially be refactored into more readable, self-explanatory code.2. Long constructor - the class contains a long constructor which can be refactored into smaller methods.3. Feature envy - the class has a lot of getters and setters for properties that belong to the QuickfixjEngine class, indicating that there might be a better design where these properties are directly accessed in the QuickfixjEngine class. | data class | 0 | 10306 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 1209 | 10306 | minor |
| 2136 | YES I found bad smells the bad smells are: 1. Duplicated Code (repetitive method implementations) 2. Feature Envy (the use of multiple clients for different entities, instead of having one client for all entities) 3. Long Method (the ProxiedNiFiClient constructor and some of the methods are relatively long and could be split into smaller methods) 4. Large Class (the ProxiedNiFiClient class has multiple methods and responsibilities, which could be split into smaller classes) 5. Feature Branching (the use of if statements in the methods to handle different entities or tokens could be handled more efficiently using polymorphism) 6. Shotgun Surgery (if the API or functionality needs to be changed, it would require changes in multiple methods and classes, making it difficult to maintain) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class ProxiedNiFiClient implements NiFiClient { private final String proxiedEntity; private final NiFiClient wrappedClient; public ProxiedNiFiClient(final NiFiClient wrappedClient, final String proxiedEntity) { this.proxiedEntity = proxiedEntity; this.wrappedClient = wrappedClient; } @Override public ControllerClient getControllerClient() { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForToken(String token) { return wrappedClient.getControllerClientForToken(token); } @Override public FlowClient getFlowClient() { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForToken(String token) { return wrappedClient.getFlowClientForToken(token); } @Override public ProcessGroupClient getProcessGroupClient() { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForToken(String token) { return wrappedClient.getProcessGroupClientForToken(token); } @Override public VersionsClient getVersionsClient() { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForToken(String token) { return wrappedClient.getVersionsClientForToken(token); } @Override public void close() throws IOException { wrappedClient.close(); } } |
blob | Duplicated Code (repetitive method implementations)2 Feature Envy (the use of multiple clients for different entities, instead of having one client for all entities)3 Long Method (the ProxiedNiFiClient constructor and some of the methods are relatively long and could be split into smaller methods)4 Large Class (the ProxiedNiFiClient class has multiple methods and responsibilities, which could be split into smaller classes)5 Feature Branching (the use of if statements in the methods to handle different entities or tokens could be handled more efficiently using polymorphism)6 Shotgun Surgery (if the API or functionality needs to be changed, it would require changes in multiple methods and classes, making it difficult to maintain) | t | f | f | . Duplicated Code (repetitive method implementations)2. Feature Envy (the use of multiple clients for different entities, instead of having one client for all entities)3. Long Method (the ProxiedNiFiClient constructor and some of the methods are relatively long and could be split into smaller methods)4. Large Class (the ProxiedNiFiClient class has multiple methods and responsibilities, which could be split into smaller classes)5. Feature Branching (the use of if statements in the methods to handle different entities or tokens could be handled more efficiently using polymorphism)6. Shotgun Surgery (if the API or functionality needs to be changed, it would require changes in multiple methods and classes, making it difficult to maintain) | blob | 0 | 13253 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiClientFactory.java/#L113-L187 | 2 | 2136 | 13253 | minor |
| 1310 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10680 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1310 | 10680 | major |
| 2456 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14524 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 1 | 2456 | 14524 | major |
| 2498 | YES I found bad smells the bad smells are: 1. No proper comments or documentation for code. 2. Unclear or misleading variable and method names. 3. Shortened, non-descriptive class name (Customer1131). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | No proper comments or documentation for code2 Unclear or misleading variable and method names3 Shortened, non-descriptive class name (Customer | t | f | f | . No proper comments or documentation for code.2. Unclear or misleading variable and method names.3. Shortened, non-descriptive class name (Customer | data class | 0 | 14649 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 2 | 2498 | 14649 | minor |
| 1066 | YES I found bad smells Bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
blob | Feature envy | t | f | f | . Feature envy | blob | 0 | 9581 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1066 | 9581 | minor |
| 2439 | ; YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14478 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 2439 | 14478 | major |
| 704 | YES, I found bad smells The bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Inconsistent naming conventions 5. Overly complex code 6. Lack of modularity 7. Poor exception handling 8. Violation of single responsibility principle | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class N4JSNewProjectWizard extends XtextNewProjectWizard { private static final ImageDescriptor NEW_PROJECT_WIZBAN_DESC = ImageRef.NEW_PROJECT_WIZBAN.asImageDescriptor() .orNull(); private static final String DIALOG_SETTINGS_SECTION_KEY = "org.eclipse.n4js.ui.wizard.project.N4JSNewProjectWizard.dialogSettings"; private static final String CREATE_GREETER_SETTINGS_KEY = "createGreeterFile"; private static final String VENDOR_ID_SETTINGS_KEY = "vendorId"; private final N4JSProjectInfo projectInfo; @Inject private IResourceDescriptions resourceDescriptions; private N4JSNewProjectWizardCreationPage newProjectWizardCreationPage; /** * Creates a new wizard container for creating and initializing a new N4JS project into the workspace. * * @param projectCreator * the project creation logic to be triggered when finishing this wizard. */ @Inject public N4JSNewProjectWizard(final IProjectCreator projectCreator) { super(projectCreator); setWindowTitle("New N4JS Project"); setNeedsProgressMonitor(true); setDefaultPageImageDescriptor(NEW_PROJECT_WIZBAN_DESC); projectInfo = new N4JSProjectInfo(); // Setup the dialog settings IDialogSettings workbenchDialogSettings = N4JSActivator.getInstance().getDialogSettings(); IDialogSettings projectWizardSettings = workbenchDialogSettings.getSection(DIALOG_SETTINGS_SECTION_KEY); if (null == projectWizardSettings) { projectWizardSettings = workbenchDialogSettings.addNewSection(DIALOG_SETTINGS_SECTION_KEY); } setDialogSettings(projectWizardSettings); } @Override public void createPageControls(Composite pageContainer) { super.createPageControls(pageContainer); IDialogSettings dialogSettings = this.getDialogSettings(); if (null != dialogSettings.get(CREATE_GREETER_SETTINGS_KEY)) { projectInfo.setCreateGreeterFile(dialogSettings.getBoolean(CREATE_GREETER_SETTINGS_KEY)); } if (null != dialogSettings.get(VENDOR_ID_SETTINGS_KEY)) { projectInfo.setVendorId(dialogSettings.get(VENDOR_ID_SETTINGS_KEY)); } } @Override public void addPages() { newProjectWizardCreationPage = new N4JSNewProjectWizardCreationPage(projectInfo); addPage(newProjectWizardCreationPage); addPage(new N4JSTestedProjectWizardPage(projectInfo, resourceDescriptions)); } @Override public boolean performFinish() { // Save the value for the create greeter file checkbox and the vendor id this.getDialogSettings().put(CREATE_GREETER_SETTINGS_KEY, projectInfo.getCreateGreeterFile()); this.getDialogSettings().put(VENDOR_ID_SETTINGS_KEY, projectInfo.getVendorId()); return super.performFinish(); } @Override public boolean canFinish() { /* * Can finish after first page for non-test projects or like normally if all pages are complete for test * projects * * This means that even for test projects the whole second page can be completely skipped. */ return (!ProjectType.TEST.equals(projectInfo.getProjectType()) && newProjectWizardCreationPage.isPageComplete()) || super.canFinish(); } @Override protected IProjectInfo getProjectInfo() { // update workingsets: newProjectWizardCreationPage.updateSelectedWorkingSets(); return projectInfo; } } |
blob | Feature envy2 Long method3 Duplicate code4 Inconsistent naming conventions5 Overly complex code6 Lack of modularity7 Poor exception handling8 Violation of single responsibility principle | t | f | f | . Feature envy2. Long method3. Duplicate code4. Inconsistent naming conventions5. Overly complex code6. Lack of modularity7. Poor exception handling8. Violation of single responsibility principle | blob | 0 | 6704 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/wizard/project/N4JSNewProjectWizard.java/#L31-L119 | 2 | 704 | 6704 | minor |
| 66 | {"response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Solaris extends OperatingSystem.Unix { @Override public String getFamilyName() { return "solaris"; } @Override protected String getOsPrefix() { return "sunos"; } @Override protected String getArch() { String arch = System.getProperty("os.arch"); if (arch.equals("i386") || arch.equals("x86")) { return "x86"; } return super.getArch(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1074 | https://github.com/linkedin/pygradle/blob/4b04b7980dc47a76b816184ebbcfe0b3f5cefadd/pygradle-plugin/src/main/groovy/com/linkedin/gradle/python/util/OperatingSystem.java/#L363-L382 | 2 | 66 | 1074 | major |
| 1359 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10776 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1359 | 10776 | major |
| 2516 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14697 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 2516 | 14697 | major |
| 184 | {"response": "YES I found bad smells", "bad smells are": ["1.Long method", "2.Use of assert", "3.Lack of comments/documentation"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextListenerStartup implements ServletContextListener { /** Configuration file path parameter name. */ public static final String IGNITE_CFG_FILE_PATH_PARAM = "IgniteConfigurationFilePath"; /** Names of started Ignite instances. */ private final Collection igniteInstanceNames = new ArrayList<>(); /** {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent evt) { ServletContext ctx = evt.getServletContext(); String cfgFile = ctx.getInitParameter(IGNITE_CFG_FILE_PATH_PARAM); Collection cfgs; GridSpringResourceContext rsrcCtx = null; if (cfgFile != null) { URL cfgUrl = null; try { cfgUrl = evt.getServletContext().getResource("/META-INF/" + cfgFile); } catch (MalformedURLException ignored) { // Ignore, we still need to try with IGNITE_HOME. } if (cfgUrl == null) // Try with IGNITE_HOME and with context class loader. cfgUrl = U.resolveIgniteUrl(cfgFile); if (cfgUrl == null) throw new IgniteException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile); IgniteBiTuple, ? extends GridSpringResourceContext> t; try { t = IgnitionEx.loadConfigurations(cfgUrl); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to load Ignite configuration.", e); } cfgs = t.get1(); rsrcCtx = t.get2(); if (cfgs.isEmpty()) throw new IgniteException("Can't find grid factory configuration in: " + cfgUrl); } else cfgs = Collections.singleton(new IgniteConfiguration()); try { assert !cfgs.isEmpty(); for (IgniteConfiguration cfg : cfgs) { assert cfg != null; Ignite ignite; synchronized (ServletContextListenerStartup.class) { try { ignite = G.ignite(cfg.getIgniteInstanceName()); } catch (IgniteIllegalStateException ignored) { ignite = IgnitionEx.start(new IgniteConfiguration(cfg), rsrcCtx); } } // Check if grid is not null - started properly. if (ignite != null) igniteInstanceNames.add(ignite.name()); } } catch (IgniteCheckedException e) { // Stop started grids only. for (String name : igniteInstanceNames) G.stop(name, true); throw new IgniteException("Failed to start Ignite.", e); } } /** {@inheritDoc} */ @Override public void contextDestroyed(ServletContextEvent evt) { // Stop started grids only. for (String name: igniteInstanceNames) G.stop(name, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ServletContextListenerStartup.class, this); } } |
blob | 1.long method, 2.use of assert, 3.lack of comments/documentation | t | t | f | 1.long method, 2.use of assert, 3.lack of comments/documentation | blob | 0 | 2104 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/web/src/main/java/org/apache/ignite/startup/servlet/ServletContextListenerStartup.java/#L95-L189 | 2 | 184 | 2104 | major |
| 1850 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: excessive use of getters and setters of other classes 3. Magic numbers: some numbers (e.g. 0) are hard-coded instead of using constants or named variables. 4. Bloated constructor: the constructor has multiple parameters, making it hard to read and understand. 5. Code duplication: some parts of the code (such as the destroy method) are duplicated in multiple places. 6. Lack of comments: some parts of the code lack comments, making it hard to understand the purpose and functionality. 7. Too many dependencies: the class depends on multiple other classes, making it tightly coupled and hard to maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | Long method2 Feature envy: excessive use of getters and setters of other classes3 Magic numbers: some numbers (eg 0) are hard-coded instead of using constants or named variables4 Bloated constructor: the constructor has multiple parameters, making it hard to read and understand 5 Code duplication: some parts of the code (such as the destroy method) are duplicated in multiple places 6 Lack of comments: some parts of the code lack comments, making it hard to understand the purpose and functionality 7 Too many dependencies: the class depends on multiple other classes, making it tightly coupled and hard to maintain | t | f | f | . Long method2. Feature envy: excessive use of getters and setters of other classes3. Magic numbers: some numbers (e.g. 0) are hard-coded instead of using constants or named variables.4. Bloated constructor: the constructor has multiple parameters, making it hard to read and understand. 5. Code duplication: some parts of the code (such as the destroy method) are duplicated in multiple places. 6. Lack of comments: some parts of the code lack comments, making it hard to understand the purpose and functionality. 7. Too many dependencies: the class depends on multiple other classes, making it tightly coupled and hard to maintain. | blob | 0 | 12188 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 1850 | 12188 | major |
| 1452 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11001 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1452 | 11001 | minor |
| 1616 | {"response": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 11474 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 1616 | 11474 | critical |
| 1244 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method | t | t | f | long method | data class | 0 | 10416 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 1244 | 10416 | critical |
| 810 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7648 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 | 2 | 810 | 7648 | major |
| 192 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class FuncLongToString extends VectorExpression { private static final long serialVersionUID = 1L; private final int inputColumn; // Transient members initialized by transientInit method. protected byte[] bytes; FuncLongToString(int inputColumn, int outputColumnNum) { super(outputColumnNum); this.inputColumn = inputColumn; } FuncLongToString() { super(); // Dummy final assignments. inputColumn = -1; } @Override public void transientInit() throws HiveException { super.transientInit(); bytes = new byte[64]; // staging area for results, to avoid new() calls } @Override public void evaluate(VectorizedRowBatch batch) throws HiveException { if (childExpressions != null) { super.evaluateChildren(batch); } LongColumnVector inputColVector = (LongColumnVector) batch.cols[inputColumn]; int[] sel = batch.selected; int n = batch.size; long[] vector = inputColVector.vector; BytesColumnVector outputColVector = (BytesColumnVector) batch.cols[outputColumnNum]; outputColVector.initBuffer(); boolean[] inputIsNull = inputColVector.isNull; boolean[] outputIsNull = outputColVector.isNull; if (n == 0) { //Nothing to do return; } // We do not need to do a column reset since we are carefully changing the output. outputColVector.isRepeating = false; if (inputColVector.isRepeating) { if (inputColVector.noNulls || !inputIsNull[0]) { // Set isNull before call in case it changes it mind. outputIsNull[0] = false; prepareResult(0, vector, outputColVector); } else { outputIsNull[0] = true; outputColVector.noNulls = false; } outputColVector.isRepeating = true; return; } if (inputColVector.noNulls) { if (batch.selectedInUse) { // CONSIDER: For large n, fill n or all of isNull array and use the tighter ELSE loop. if (!outputColVector.noNulls) { for(int j = 0; j != n; j++) { final int i = sel[j]; // Set isNull before call in case it changes it mind. outputIsNull[i] = false; prepareResult(i, vector, outputColVector); } } else { for(int j = 0; j != n; j++) { final int i = sel[j]; prepareResult(i, vector, outputColVector); } } } else { if (!outputColVector.noNulls) { // Assume it is almost always a performance win to fill all of isNull so we can // safely reset noNulls. Arrays.fill(outputIsNull, false); outputColVector.noNulls = true; } for(int i = 0; i != n; i++) { prepareResult(i, vector, outputColVector); } } } else /* there are nulls in the inputColVector */ { // Carefully handle NULLs... outputColVector.noNulls = false; if (batch.selectedInUse) { for(int j=0; j != n; j++) { int i = sel[j]; outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } else { for(int i = 0; i != n; i++) { outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } } } /* Evaluate result for position i (using bytes[] to avoid storage allocation costs) * and set position i of the output vector to the result. */ abstract void prepareResult(int i, long[] vector, BytesColumnVector outputColVector); @Override public String vectorExpressionParameters() { return getColumnParamString(0, inputColumn); } @Override public VectorExpressionDescriptor.Descriptor getDescriptor() { return (new VectorExpressionDescriptor.Builder()).setMode( VectorExpressionDescriptor.Mode.PROJECTION).setNumArguments(1).setInputExpressionTypes( VectorExpressionDescriptor.InputExpressionType.COLUMN).setArgumentTypes( VectorExpressionDescriptor.ArgumentType.INT_FAMILY).build(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2216 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/expressions/FuncLongToString.java/#L36-L172 | 2 | 192 | 2216 | minor |
| 419 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BeamIntersectRel extends Intersect implements BeamRelNode { public BeamIntersectRel( RelOptCluster cluster, RelTraitSet traits, List inputs, boolean all) { super(cluster, traits, inputs, all); } @Override public SetOp copy(RelTraitSet traitSet, List inputs, boolean all) { return new BeamIntersectRel(getCluster(), traitSet, inputs, all); } @Override public PTransform, PCollection> buildPTransform() { return new BeamSetOperatorRelBase(this, BeamSetOperatorRelBase.OpType.INTERSECT, all); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 4239 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamIntersectRel.java/#L37-L52 | 2 | 419 | 4239 | minor |
| 497 | { "error": "Invalid input. The provided code snippet is incomplete or not formatted correctly." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | f | f | f | data class | 0 | 5043 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 1 | 497 | 5043 | major | ||
| 602 | YES I found bad smells The bad smells are: 1. Code duplication 2. Magic numbers 3. Use of raw types in collections 4. Use of setter methods instead of constructor injection 5. Lack of encapsulation for fields 6. Violations of single responsibility principle (validation and manipulation in same method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | Code duplication2 Magic numbers3 Use of raw types in collections4 Use of setter methods instead of constructor injection5 Lack of encapsulation for fields6 Violations of single responsibility principle (validation and manipulation in same method) | t | f | f | . Code duplication2. Magic numbers3. Use of raw types in collections4. Use of setter methods instead of constructor injection5. Lack of encapsulation for fields6. Violations of single responsibility principle (validation and manipulation in same method) | data class | 0 | 6009 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 2 | 602 | 6009 | major |
| 625 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
data class | long method | t | t | f | long method | data class | 0 | 6254 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 1 | 625 | 6254 | major |
| 5107 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } } |
blob | long method | t | t | f | long method | blob | 0 | 14309 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 | 1 | 5107 | 14309 | minor |
| 805 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7623 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 | 2 | 805 | 7623 | minor |
| 580 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 5785 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 580 | 5785 | minor |
| 2068 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JAXRSOutInterceptor extends AbstractOutDatabindingInterceptor { private static final Logger LOG = LogUtils.getL7dLogger(JAXRSOutInterceptor.class); private static final ResourceBundle BUNDLE = BundleUtils.getBundle(JAXRSOutInterceptor.class); public JAXRSOutInterceptor() { super(Phase.MARSHAL); } public void handleMessage(Message message) { ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); try { processResponse(providerFactory, message); } finally { ServerProviderFactory.releaseRequestState(providerFactory, message); } } @SuppressWarnings("resource") // Response shouldn't be closed here private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.isEmpty()) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response)responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class .getName()); serializeMessage(providerFactory, message, response, ori, true); } private int getStatus(Message message, int defaultValue) { Object customStatus = message.getExchange().get(Message.RESPONSE_CODE); return customStatus == null ? defaultValue : (Integer)customStatus; } private void serializeMessage(ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) { ResponseImpl response = (ResponseImpl)JAXRSUtils.copyResponseIfNeeded(theResponse); final Exchange exchange = message.getExchange(); boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod()); Object entity = response.getActualEntity(); if (headResponse && entity != null) { LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString()); entity = null; } Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke(); Annotation[] annotations = null; Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[]{}; Annotation[] responseAnns = response.getEntityAnnotations(); if (responseAnns != null) { annotations = new Annotation[staticAnns.length + responseAnns.length]; System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length); System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length); } else { annotations = staticAnns; } response.setStatus(getActualStatus(response.getStatus(), entity)); response.setEntity(entity, annotations); // Prepare the headers MultivaluedMap responseHeaders = prepareResponseHeaders(message, response, entity, firstTry); // Run the filters try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } // Write the entity entity = InjectionUtils.getEntity(response.getActualEntity()); setResponseStatus(message, getActualStatus(response.getStatus(), entity)); if (entity == null) { if (!headResponse) { responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0"); if (MessageUtils.getContextualBoolean(message, "remove.content.type.for.empty.response", false)) { responseHeaders.remove(HttpHeaders.CONTENT_TYPE); message.remove(Message.CONTENT_TYPE); } } HttpUtils.convertHeaderValuesToString(responseHeaders, true); return; } Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS); boolean ignoreWriters = ignoreWritersProp != null && Boolean.valueOf(ignoreWritersProp.toString()); if (ignoreWriters) { writeResponseToStream(message.getContent(OutputStream.class), entity); return; } MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE)); Class serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null; Class targetType = InjectionUtils.getRawResponseClass(entity); Type genericType = InjectionUtils.getGenericResponseType(invoked, serviceCls, response.getActualEntity(), targetType, exchange); targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType); annotations = response.getEntityAnnotations(); List writers = providerFactory .createMessageBodyWriterInterceptor(targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings()); OutputStream outOriginal = message.getContent(OutputStream.class); if (writers == null || writers.isEmpty()) { writeResponseErrorMessage(message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType); return; } try { boolean checkWriters = false; if (responseMediaType.isWildcardSubtype()) { Produces pM = AnnotationUtils.getMethodAnnotation(ori == null ? null : ori.getAnnotatedMethod(), Produces.class); Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class); checkWriters = pM == null && pC == null; } responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Response content type is: " + finalResponseContentType); } responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType); message.put(Message.CONTENT_TYPE, finalResponseContentType); boolean enabled = checkBufferingMode(message, writers, firstTry); try { try { JAXRSUtils.writeMessageBody(writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message); if (isResponseRedirected(message)) { return; } checkCachedStream(message, outOriginal, enabled); } finally { if (enabled) { OutputStream os = message.getContent(OutputStream.class); if (os != outOriginal && os instanceof CachedOutputStream) { os.close(); } message.setContent(OutputStream.class, outOriginal); message.put(XMLStreamWriter.class.getName(), null); } } } catch (Throwable ex) { logWriteError(firstTry, targetType, responseMediaType); handleWriteException(providerFactory, message, ex, firstTry); } } private MultivaluedMap prepareResponseHeaders(Message message, ResponseImpl response, Object entity, boolean firstTry) { MultivaluedMap responseHeaders = response.getMetadata(); @SuppressWarnings("unchecked") Map> userHeaders = (Map>)message.get(Message.PROTOCOL_HEADERS); if (firstTry && userHeaders != null) { responseHeaders.putAll(userHeaders); } if (entity != null) { Object customContentType = responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE); if (customContentType == null) { String initialResponseContentType = (String)message.get(Message.CONTENT_TYPE); if (initialResponseContentType != null) { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, initialResponseContentType); } } else { message.put(Message.CONTENT_TYPE, customContentType.toString()); } } message.put(Message.PROTOCOL_HEADERS, responseHeaders); setResponseDate(responseHeaders, firstTry); return responseHeaders; } private MediaType getResponseMediaType(Object mediaTypeHeader) { MediaType responseMediaType; if (mediaTypeHeader instanceof MediaType) { responseMediaType = (MediaType)mediaTypeHeader; } else { responseMediaType = mediaTypeHeader == null ? MediaType.WILDCARD_TYPE : JAXRSUtils.toMediaType(mediaTypeHeader.toString()); } return responseMediaType; } private int getActualStatus(int status, Object responseObj) { if (status == -1) { return responseObj == null ? 204 : 200; } return status; } private boolean checkBufferingMode(Message m, List writers, boolean firstTry) { if (!firstTry) { return false; } WriterInterceptor last = writers.get(writers.size() - 1); MessageBodyWriter w = ((WriterInterceptorMBW)last).getMBW(); Object outBuf = m.getContextualProperty(OUT_BUFFERING); boolean enabled = PropertyUtils.isTrue(outBuf); boolean configurableProvider = w instanceof AbstractConfigurableProvider; if (!enabled && outBuf == null && configurableProvider) { enabled = ((AbstractConfigurableProvider)w).getEnableBuffering(); } if (enabled) { boolean streamingOn = configurableProvider && ((AbstractConfigurableProvider)w).getEnableStreaming(); if (streamingOn) { m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter()); } else { m.setContent(OutputStream.class, new CachedOutputStream()); } } return enabled; } private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled) throws Exception { XMLStreamWriter writer = null; if (enabled) { writer = m.getContent(XMLStreamWriter.class); } else { writer = (XMLStreamWriter)m.get(XMLStreamWriter.class.getName()); } if (writer instanceof CachingXmlEventWriter) { CachingXmlEventWriter cache = (CachingXmlEventWriter)writer; if (cache.getEvents().size() != 0) { XMLStreamWriter origWriter = null; try { origWriter = StaxUtils.createXMLStreamWriter(osOriginal); for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origWriter); } } finally { StaxUtils.close(origWriter); } } m.setContent(XMLStreamWriter.class, null); return; } if (enabled) { OutputStream os = m.getContent(OutputStream.class); if (os != osOriginal && os instanceof CachedOutputStream) { CachedOutputStream cos = (CachedOutputStream)os; if (cos.size() != 0) { cos.writeCacheTo(osOriginal); } } } } private void logWriteError(boolean firstTry, Class cls, MediaType ct) { if (firstTry) { JAXRSUtils.logMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, ct); } } private void handleWriteException(ServerProviderFactory pf, Message message, Throwable ex, boolean firstTry) { Response excResponse = null; if (firstTry) { excResponse = JAXRSUtils.convertFaultToResponse(ex, message); } else { message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE); } if (excResponse == null) { setResponseStatus(message, 500); throw new Fault(ex); } serializeMessage(pf, message, excResponse, null, false); } private void writeResponseErrorMessage(Message message, OutputStream out, String name, Class cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } } private MediaType checkFinalContentType(MediaType mt, List writers, boolean checkWriters) { if (checkWriters) { int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1; MessageBodyWriter writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW(); Produces pm = writer.getClass().getAnnotation(Produces.class); if (pm != null) { List sorted = JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM); mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0); } } if (mt.isWildcardType() || mt.isWildcardSubtype()) { if ("application".equals(mt.getType()) || mt.isWildcardType()) { mt = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { throw ExceptionUtils.toNotAcceptableException(null, null); } } return mt; } private void setResponseDate(MultivaluedMap headers, boolean firstTry) { if (!firstTry || headers.containsKey(HttpHeaders.DATE)) { return; } SimpleDateFormat format = HttpUtils.getHttpDateFormat(); headers.putSingle(HttpHeaders.DATE, format.format(new Date())); } private boolean isResponseAlreadyHandled(Message m) { return isResponseAlreadyCommited(m) || isResponseRedirected(m); } private boolean isResponseAlreadyCommited(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.RESPONSE_COMMITED)); } private boolean isResponseRedirected(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.REQUEST_REDIRECTED)); } private void writeResponseToStream(OutputStream os, Object responseObj) { try { byte[] bytes = responseObj.toString().getBytes(StandardCharsets.UTF_8); os.write(bytes, 0, bytes.length); } catch (Exception ex) { LOG.severe("Problem with writing the data to the output stream"); ex.printStackTrace(); throw new RuntimeException(ex); } } private void setResponseStatus(Message message, int status) { message.put(Message.RESPONSE_CODE, status); boolean responseHeadersCopied = isResponseHeadersCopied(message); if (responseHeadersCopied) { HttpServletResponse response = (HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE); response.setStatus(status); } } // Some CXF interceptors such as FIStaxOutInterceptor will indirectly initiate // an early copying of response code and headers into the HttpServletResponse // TODO : Pushing the filter processing and copying response headers into say // PRE-LOGICAl and PREPARE_SEND interceptors will most likely be a good thing // however JAX-RS MessageBodyWriters are also allowed to add response headers // which is reason why a MultipartMap parameter in MessageBodyWriter.writeTo // method is modifiable. Thus we do need to know if the initial copy has already // occurred: for now we will just use to ensure the correct status is set private boolean isResponseHeadersCopied(Message message) { return PropertyUtils.isTrue(message.get(AbstractHTTPDestination.RESPONSE_HEADERS_COPIED)); } public void handleFault(Message message) { // complete } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13001 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java/#L73-L495 | 1 | 2068 | 13001 | minor |
| 2596 | { "response": "YES I found bad smells" , "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 15008 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 | 1 | 2596 | 15008 | major |
| 1019 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method2 Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data | t | f | f | . Long method2. Feature envy: Contains a method (getContent) that manipulates a data structure belonging to another class (List content) instead of operating on its own data. | data class | 0 | 9341 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 1019 | 9341 | critical |
| 1940 | YES I found bad smells The bad smells are: 1. Magic numbers 2. Long method 3. Feature envy 4. Inconsistent use of spaces and indentation 5. Excessive use of comments 6. Code duplication 7. Unnecessary imports 8. Inconsistent and confusing variable names 9. Use of generic types without specifying the type 10. Inefficient code (e.g. using multiple if statements instead of a switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
blob | Magic numbers 2 Long method 3 Feature envy 4 Inconsistent use of spaces and indentation 5 Excessive use of comments 6 Code duplication 7 Unnecessary imports 8 Inconsistent and confusing variable names 9 Use of generic types without specifying the type | t | f | f | . Magic numbers 2. Long method 3. Feature envy 4. Inconsistent use of spaces and indentation 5. Excessive use of comments 6. Code duplication 7. Unnecessary imports 8. Inconsistent and confusing variable names 9. Use of generic types without specifying the type | blob | 0 | 12484 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 1940 | 12484 | minor |
| 2562 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14843 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 2562 | 14843 | major |
| 2685 | {"result": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | long method | t | t | f | long method | blob | 0 | 15277 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 1 | 2685 | 15277 | minor |
| 2163 | { "message": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | long method | t | t | f | long method | data class | 0 | 13330 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 2163 | 13330 | minor |
| 1455 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Code repetition 4. Lack of comments/documentation 5. Poor naming conventions for variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } } |
blob | Long method2 Feature envy3 Code repetition4 Lack of comments/documentation5 Poor naming conventions for variables and methods | t | f | f | . Long method2. Feature envy3. Code repetition4. Lack of comments/documentation5. Poor naming conventions for variables and methods | blob | 0 | 11008 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 | 2 | 1455 | 11008 | major |
| 976 | {"message":"YES, I found bad smells", "the bad smells are":{ "1":"Long method", "2":"Feature envy" } } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | 1: long method, 2: feature envy | t | t | f | 1: long method, 2: feature envy | blob | 0 | 8781 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 2 | 976 | 8781 | minor |
| 2235 | {"output": "YES I found bad smells. the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13609 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 1 | 2235 | 13609 | minor |
| 2665 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 15202 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 2665 | 15202 | minor |
| 2240 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } } |
blob | data class | t | t | f | data class | blob | 0 | 13619 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 | 1 | 2240 | 13619 | major |
| 793 | { "YES I found bad smells": true, "the bad smells are": [ "1. Long method", "2. Feature envy", "3. Many instance variables" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
blob | 1. long method, 2. feature envy, 3. many instance variables | t | t | f | 1. long method, 2. feature envy, 3. many instance variables | blob | 0 | 7553 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 793 | 7553 | minor |
| 2295 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Inconsistent formatting 3. Code duplication 4. Magic numbers/unclear purpose of code 5. Use of assert statement as hack | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Feature envy2 Inconsistent formatting3 Code duplication4 Magic numbers/unclear purpose of code5 Use of assert statement as hack | t | f | f | . Feature envy2. Inconsistent formatting3. Code duplication4. Magic numbers/unclear purpose of code5. Use of assert statement as hack | data class | 0 | 13990 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 2295 | 13990 | minor |
| 1332 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10716 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 1332 | 10716 | critical |
| 292 | YES I found bad smells The bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Null checks/Exception handling inside a method 5. Magic numbers 6. Multiple assertions in one test method 7. Testing implementation details instead of behavior 8. Lack of descriptive method and variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
data class | Duplicated code2 Long method3 Feature envy4 Null checks/Exception handling inside a method5 Magic numbers6 Multiple assertions in one test method7 Testing implementation details instead of behavior8 Lack of descriptive method and variable names | t | f | f | . Duplicated code2. Long method3. Feature envy4. Null checks/Exception handling inside a method5. Magic numbers6. Multiple assertions in one test method7. Testing implementation details instead of behavior8. Lack of descriptive method and variable names | data class | 0 | 3077 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 292 | 3077 | critical |
| 1576 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11350 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 2 | 1576 | 11350 | major |
| 3215 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 5113 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 2 | 3215 | 5113 | minor |
| 2598 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15010 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 2598 | 15010 | minor |
| 1229 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10360 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 1229 | 10360 | major |
| 3801 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9635 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1280-L1292 | 2 | 3801 | 9635 | minor | ||
| 2474 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 14583 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 1 | 2474 | 14583 | minor |
| 437 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder(float k1, float b) { this.similarity = new BM25Similarity(k1, b); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 4292 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L78-L80 | 1 | 437 | 4292 | minor |
| 597 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5956 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 2 | 597 | 5956 | major |
| 3 | {"response": "YES I found bad smells","detected_bad_smells":[ "1. Long Method", "2. Data Class" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 554 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 3 | 554 | major |
| 42 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 805 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 42 | 805 | major |
| 815 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7659 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 2 | 815 | 7659 | critical |
| 668 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
blob | long method | t | t | f | long method | blob | 0 | 6550 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 1 | 668 | 6550 | minor |
| 600 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5993 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 600 | 5993 | major |
| 2049 | {"response": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12883 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 2 | 2049 | 12883 | minor |
| 1819 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent indentation 4. Nested conditional statements 5. Unnecessary commenting 6. Mixing logic and data extraction in one method 7. Lack of cohesive naming conventions 8. Violation of single responsibility principle | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | Long method2 Feature envy3 Inconsistent indentation4 Nested conditional statements5 Unnecessary commenting6 Mixing logic and data extraction in one method7 Lack of cohesive naming conventions8 Violation of single responsibility principle | t | f | f | . Long method2. Feature envy3. Inconsistent indentation4. Nested conditional statements5. Unnecessary commenting6. Mixing logic and data extraction in one method7. Lack of cohesive naming conventions8. Violation of single responsibility principle | blob | 0 | 12093 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 2 | 1819 | 12093 | minor |
| 317 | { "output": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 3255 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 1 | 317 | 3255 | major |
| 343 | { "output": "YES I found bad smells the bad smells are: 1. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NamespaceFilter extends XMLFilterImpl { private static final InputSource EMPTY_INPUT_SOURCE = new InputSource(new ByteArrayInputStream(new byte[0])); public NamespaceFilter(XMLReader xmlReader) { super(xmlReader); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return EMPTY_INPUT_SOURCE; } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 3503 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/sun/JaxbSun.java/#L96-L106 | 1 | 343 | 3503 | major |
| 2310 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14096 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2310 | 14096 | major |
| 255 | {"result": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class Prefixes { /** * The SI “deca” prefix. This is the only SI prefix encoded on two letters instead than one. * It can be represented by the CJK compatibility character “㍲”, but use of those characters * is generally not recommended outside of Chinese, Japanese or Korean texts. */ private static final String DECA = "da"; /** * The SI prefixes in increasing order. The only two-letters prefix – “da” – is encoded using the JCK compatibility * character “㍲”. The Greek letter μ is repeated twice: the U+00B5 character for micro sign (this is the character * that Apache SIS uses in unit symbols) and the U+03BC character for the Greek small letter “mu” (the later is the * character that appears when decomposing JCK compatibility characters with {@link java.text.Normalizer}). * Both characters have same appearance but different values. * * For each prefix at index i, the multiplication factor is given by 10 raised to power {@code POWERS[i]}. */ private static final char[] PREFIXES = {'E','G','M','P','T','Y','Z','a','c','d','f','h','k','m','n','p','y','z','µ','μ','㍲'}; private static final byte[] POWERS = {18, 9, 6, 15, 12, 24, 21,-18, -2, -1,-15, 2, 3, -3, -9,-12,-24,-21, -6, -6, 1}; /** * The SI prefixes from smallest to largest. Power of tens go from -24 to +24 inclusive with a step of 3, * except for the addition of -2, -1, +1, +2 and the omission of 0. * * @see #symbol(double, int) */ private static final char[] ENUM = {'y','z','a','f','p','n','µ','m','c','d','㍲','h','k','M','G','T','P','E','Z','Y'}; /** * The maximal power of 1000 for the prefixes in the {@link #ENUM} array. Note that 1000⁸ = 1E+24. */ static final int MAX_POWER = 8; /** * The converters for SI prefixes, created when first needed. * * @see #converter(char) */ private static final LinearConverter[] CONVERTERS = new LinearConverter[POWERS.length]; /** * Do not allow instantiation of this class. */ private Prefixes() { } /** * Returns the converter for the given SI prefix, or {@code null} if none. * Those converters are created when first needed and cached for reuse. */ static LinearConverter converter(final char prefix) { final int i = Arrays.binarySearch(PREFIXES, prefix); if (i < 0) { return null; } synchronized (CONVERTERS) { LinearConverter c = CONVERTERS[i]; if (c == null) { final int p = POWERS[i]; final double numerator, denominator; if (p >= 0) { numerator = MathFunctions.pow10(p); denominator = 1; } else { numerator = 1; denominator = MathFunctions.pow10(-p); } c = LinearConverter.scale(numerator, denominator); CONVERTERS[i] = c; } return c; } } /** * Returns the SI prefix symbol for the given scale factor, or 0 if none. * * @param scale the scale factor. * @param power the unit power. For example if we are scaling m², then this is 2. * @return the prefix, or 0 if none. */ static char symbol(double scale, final int power) { switch (power) { case 0: return 0; case 1: break; case 2: scale = Math.sqrt(scale); break; case 3: scale = Math.cbrt(scale); break; default: scale = Math.pow(scale, 1.0/power); } final int n = Numerics.toExp10(Math.getExponent(scale)) + 1; if (AbstractConverter.epsilonEquals(MathFunctions.pow10(n), scale)) { int i = Math.abs(n); switch (i) { case 0: return 0; case 1: // Fallthrough case 2: break; default: { if (i > (MAX_POWER*3) || (i % 3) != 0) { return 0; } i = i/3 + 2; break; } } return ENUM[n >= 0 ? (MAX_POWER+1) + i : (MAX_POWER+2) - i]; } return 0; } /** * Returns the concatenation of the given prefix with the given unit symbol. */ static String concat(final char prefix, final String unit) { return (prefix == '㍲') ? DECA + unit : prefix + unit; } /** * Returns the unit for the given symbol, taking the SI prefix in account. The given string is usually a single symbol * like "km", but may be an expression like "m³" or "m/s" if the given symbol is explicitly registered as an item that * {@link Units#get(String)} recognizes. This method does not perform any arithmetic operation on {@code Unit}, * except a check for the exponent. * * @param uom a symbol compliant with the rules documented in {@link AbstractUnit#symbol}. * @return the unit for the given symbol, or {@code null} if no unit is found. */ static Unit getUnit(final String uom) { Unit unit = Units.get(uom); if (unit == null && uom.length() >= 2) { int s = 1; char prefix = uom.charAt(0); if (prefix == 'd' && uom.charAt(1) == 'a') { prefix = '㍲'; // Converse of above 'concat(char, String)' method. s = 2; // Skip "da", which we represent by '㍲'. } unit = Units.get(uom.substring(s)); if (AbstractUnit.isPrefixable(unit)) { LinearConverter c = Prefixes.converter(prefix); if (c != null) { String symbol = unit.getSymbol(); final int power = ConventionalUnit.power(symbol); if (power != 0) { if (power != 1) { c = LinearConverter.pow(c, power, false); } symbol = Prefixes.concat(prefix, symbol); return new ConventionalUnit<>((AbstractUnit) unit, c, symbol.intern(), (byte) 0, (short) 0); } } } unit = null; } return unit; } /** * If the given system unit should be replaced by pseudo-unit for the purpose of formatting, * returns that pseudo-unit. Otherwise returns {@code null}. This method is for handling the * Special case of {@link Units#KILOGRAM}, to be replaced by {@link Units#GRAM} so a prefix * can be computed. The kilogram may appear in an expression like "kg/m", which we want to * replace by "g/m". We do that by dividing the unit by 1000 (the converter for "milli" prefix). */ @SuppressWarnings("unchecked") static > ConventionalUnit pseudoSystemUnit(final SystemUnit unit) { if ((unit.scope & ~UnitRegistry.SI) == 0 && unit.dimension.numeratorIs('M')) { if (unit == Units.KILOGRAM) { return (ConventionalUnit) Units.GRAM; // Optimization for a common case. } else { String symbol = unit.getSymbol(); if (symbol != null && symbol.length() >= 3 && symbol.startsWith("kg") && !AbstractUnit.isSymbolChar(symbol.codePointAt(2))) { symbol = symbol.substring(1); UnitConverter c = converter('m'); return new ConventionalUnit<>(unit, c, symbol, UnitRegistry.PREFIXABLE, (short) 0).unique(symbol); } } } return null; } } |
blob | data class | t | t | f | data class | blob | 0 | 2751 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-utility/src/main/java/org/apache/sis/measure/Prefixes.java/#L37-L216 | 1 | 255 | 2751 | major |
| 2436 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Complicated conditionals 6. N/A check 7. Non-descriptive variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class SearchFirstStringNode extends Node { private static final int[] UNINTIALIZED_CACHED_INDICES = new int[0]; private final VectorLengthProfile targetLengthProfile = VectorLengthProfile.create(); private final VectorLengthProfile elementsLengthProfile = VectorLengthProfile.create(); private final ValueProfile targetClassProfile = ValueProfile.createClassProfile(); private final ValueProfile elementsClassProfile = ValueProfile.createClassProfile(); @Child private StringEqualsNode stringEquals = CompareStringNode.createEquals(); @Child private CompareStringNode stringStartsWith; @Child private StringEqualsNode equalsDuplicate; private final NACheck elementsNACheck = NACheck.create(); private final NACheck targetNACheck = NACheck.create(); private final BranchProfile everFoundDuplicate = BranchProfile.create(); private final BranchProfile seenInvalid = BranchProfile.create(); /** Instead of using the notFoundStartIndex we use NA. */ private final boolean useNAForNotFound; private final boolean exactMatch; @CompilationFinal(dimensions = 1) private int[] cachedIndices; private SearchFirstStringNode(boolean exactMatch, boolean useNAForNotFound) { this.exactMatch = exactMatch; this.useNAForNotFound = useNAForNotFound; if (!exactMatch) { stringStartsWith = CompareStringNode.createStartsWith(); } } public RAbstractIntVector apply(RAbstractStringVector target, RAbstractStringVector elements, int notFoundStartIndex, RStringVector names) { RAbstractStringVector targetProfiled = targetClassProfile.profile(target); RAbstractStringVector elementsProfiled = elementsClassProfile.profile(elements); int targetLength = targetLengthProfile.profile(targetProfiled.getLength()); int elementsLength = elementsLengthProfile.profile(elementsProfiled.getLength()); targetNACheck.enable(target); elementsNACheck.enable(elements); if (cachedIndices == UNINTIALIZED_CACHED_INDICES) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = searchCached(targetProfiled, targetLength, elementsProfiled, elementsLength, names); } if (cachedIndices != null) { if (!isCacheValid(targetProfiled, targetLength, elementsProfiled, elementsLength, cachedIndices)) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = null; // set to generic // fallthrough to generic } else { assert sameVector(searchCached(target, targetLength, elements, elementsLength, names), cachedIndices); return RDataFactory.createIntVector(cachedIndices, true, names); } } return searchGeneric(targetProfiled, targetLength, elementsProfiled, elementsLength, notFoundStartIndex, false, names); } public static SearchFirstStringNode createNode(boolean exactMatch, boolean useNAForNotFound) { return new SearchFirstStringNode(exactMatch, useNAForNotFound); } private int[] searchCached(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, RStringVector names) { if (exactMatch) { RAbstractIntVector genericResult = searchGeneric(target, targetLength, elements, elementsLength, -1, true, names); if (genericResult != null) { return genericResult.materialize().getReadonlyData(); } } return null; } private boolean isCacheValid(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int[] cached) { int cachedLength = cached.length; if (elementsLength != cachedLength) { seenInvalid.enter(); return false; } for (int i = 0; i < cachedLength; i++) { int cachedIndex = cached[i]; String cachedElement = elements.getDataAt(i); int cachedElementHash = cachedElement.hashCode(); assert !elementsNACheck.check(cachedElement) && cachedElement.length() > 0; int cachedTranslatedIndex = cachedIndex - 1; for (int j = 0; j < cachedTranslatedIndex; j++) { String targetString = target.getDataAt(j); if (!targetNACheck.check(targetString) && stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } if (cachedTranslatedIndex < targetLength) { String targetString = target.getDataAt(cachedTranslatedIndex); if (!targetNACheck.check(targetString) && !stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } else { seenInvalid.enter(); return false; } } return true; } private static boolean sameVector(int[] a, int[] b) { if (a == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } private final BranchProfile notFoundProfile = BranchProfile.create(); private final ConditionProfile hashingProfile = ConditionProfile.createBinaryProfile(); private RAbstractIntVector searchGeneric(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int notFoundStartIndex, boolean nullOnNotFound, RStringVector names) { int[] indices = new int[elementsLength]; boolean resultComplete = true; long hashingCost = targetLength * 10L + 10 /* constant overhead */; long lookupCost = elementsLength * 2L; long nestedLoopCost = targetLength * (long) elementsLength; NonRecursiveHashMapCharacter map; if (hashingProfile.profile(nestedLoopCost > hashingCost + lookupCost)) { map = new NonRecursiveHashMapCharacter(targetLength); for (int i = 0; i < targetLength; i++) { String name = target.getDataAt(i); if (!targetNACheck.check(name)) { map.put(name, i); } } } else { map = null; } int notFoundIndex = notFoundStartIndex; for (int i = 0; i < elementsLength; i++) { String element = elements.getDataAt(i); boolean isElementNA = elementsNACheck.check(element) || element.length() == 0; if (!isElementNA) { int index; if (map != null) { index = map.get(element); if (!exactMatch && index < 0) { // the map is only good for exact matches index = findNonExactIndex(target, targetLength, element); } } else { index = findIndex(target, targetLength, element); } if (index >= 0) { indices[i] = index + 1; continue; } } notFoundProfile.enter(); if (nullOnNotFound) { return null; } else { int prevDuplicateIndex = -1; if (!isElementNA) { prevDuplicateIndex = findFirstDuplicate(elements, element, i); } int nextIndex; if (prevDuplicateIndex == -1) { if (useNAForNotFound) { resultComplete = false; nextIndex = RRuntime.INT_NA; } else { nextIndex = ++notFoundIndex; } } else { nextIndex = indices[prevDuplicateIndex]; } indices[i] = nextIndex; } } return RDataFactory.createIntVector(indices, resultComplete && elements.isComplete(), names); } private int findNonExactIndex(RAbstractStringVector target, int targetLength, String element) { assert !exactMatch; int nonExactIndex = -1; for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { return -1; } } } } return nonExactIndex; } private int findIndex(RAbstractStringVector target, int targetLength, String element) { int nonExactIndex = -1; int elementHash = element.hashCode(); for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringEquals.executeCompare(element, elementHash, targetValue)) { return j; } if (!exactMatch) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { nonExactIndex = -2; } } } } } return nonExactIndex; } private int findFirstDuplicate(RAbstractStringVector elements, String element, int currentIndex) { if (equalsDuplicate == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); equalsDuplicate = insert(CompareStringNode.createEquals()); } int elementHash = element.hashCode(); for (int j = 0; j < currentIndex; j++) { String otherElement = elements.getDataAt(j); if (!targetNACheck.check(otherElement) && equalsDuplicate.executeCompare(element, elementHash, otherElement)) { everFoundDuplicate.enter(); return j; } } return -1; } abstract static class CompareStringNode extends Node { public abstract boolean executeCompare(String a, String b); public static StringEqualsNode createEquals() { return new StringEqualsNode(); } public static StringStartsWithNode createStartsWith() { return new StringStartsWithNode(); } public static class StringEqualsNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); private final ConditionProfile hashEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(a.hashCode() != b.hashCode())) { return false; } return a.equals(b); } } public final boolean executeCompare(String a, int aHash, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(aHash != b.hashCode())) { return false; } return a.equals(b); } } } private static class StringStartsWithNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { return a.startsWith(b); } } } } } |
blob | Long method 2 Feature envy 3 Duplicate code 4 Magic numbers 5 Complicated conditionals 6 N/A check 7 Non-descriptive variable names | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Complicated conditionals 6. N/A check 7. Non-descriptive variable names | blob | 0 | 14469 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/SearchFirstStringNode.java/#L46-L361 | 2 | 2436 | 14469 | minor |
| 1070 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 9598 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 2 | 1070 | 9598 | minor |
| 661 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | f | f | f | data class | 0 | 6434 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 2 | 661 | 6434 | critical | ||
| 2045 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | long method | t | t | f | long method | data class | 0 | 12871 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 2045 | 12871 | minor |
| 837 | YES I found bad smells the bad smells are: 1.Feature envy 2.Data class 3.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } } |
blob | Feature envy2Data class3Long method | t | f | f | .Feature envy2.Data class3.Long method | blob | 0 | 7771 | https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 | 2 | 837 | 7771 | minor |
| 990 | {"message": "YES I found bad smells", "bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class MigrationLink { int source; int target; Migration[] migrations; public MigrationLink(int source, int target, Migration[] migrations) { this.source = source; this.target = target; this.migrations = migrations; } } |
data class | blob | t | t | f | blob | data class | 0 | 9019 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java/#L113-L122 | 1 | 990 | 9019 | major |
| 2481 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14598 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 2481 | 14598 | minor |
| 5275 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14747 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5275 | 14747 | minor | ||
| 687 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6633 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 2 | 687 | 6633 | major |
| 268 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | long method | t | t | f | long method | data class | 0 | 2887 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 268 | 2887 | minor |
| 1416 | {"response": "YES I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 10912 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 1416 | 10912 | critical |
| 17 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DimsDataList implements Serializable { /** * */ private static final long serialVersionUID = -5902704017223885965L; private List dimsData; private boolean expression; public DimsDataList() { } public DimsDataList(List chunk) { dimsData = chunk; } public DimsDataList(int[] dataShape) throws Exception { try { // For now we just assume the first dimensions are the slow ones to make an axis out // of. Later read the axis from the meta list but we do not have examples of this so // far. int xaxis=-1,yaxis=-1; for (int i = 0; i=0; i--) { if (dataShape[i]>1) { if (yaxis<0) { getDimsData(i).setPlotAxis(AxisType.Y); yaxis = i; continue; } else if (xaxis<0) { getDimsData(i).setPlotAxis(AxisType.X); xaxis = i; continue; } } } // If we only found a y it may be a multiple-dimension set with only 1D possible. // In that case change y to x. if (yaxis>-1 && xaxis<0) { getDimsData(yaxis).setPlotAxis(AxisType.X); } } finally { //file.close(); } } public Iterable iterable() { return dimsData; } public void add(DimsData dimension) { if (dimsData==null) dimsData = new ArrayList(3); if (dimsData.size()>dimension.getDimension() && dimension.getDimension()>-1) { dimsData.set(dimension.getDimension(), dimension); } else { dimsData.add(dimension); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dimsData == null) ? 0 : dimsData.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DimsDataList other = (DimsDataList) obj; if (dimsData == null) { if (other.dimsData != null) return false; } else if (!dimsData.equals(other.dimsData)) return false; return true; } public static Object[] getDefault() { return new DimsData[]{new DimsData(0)}; } public Object[] getElements() { if (dimsData==null) return null; return dimsData.toArray(new DimsData[dimsData.size()]); } public int size() { if (dimsData==null) return 0; return dimsData.size(); } public DimsData getDimsData(int i) { if (dimsData==null) return null; return dimsData.get(i); } public Iterator iterator() { if (dimsData==null) return null; return dimsData.iterator(); } public void clear() { if (dimsData!=null) dimsData.clear(); } public String toString() { return toString(null); } public String toString(int[] shape) { final StringBuilder buf = new StringBuilder(); buf.append("[ "); int index = 0; for (DimsData d : dimsData) { final int upper = shape!=null ? shape[index] : -1; buf.append(d.getUserString(upper)); if (d!=dimsData.get(dimsData.size()-1)) buf.append(", "); ++index; } buf.append(" ]"); return buf.toString(); } public boolean isRangeDefined() { for (DimsData data : iterable()) { if (data.getSliceRange()!=null) return true; } return false; } public int getAxisCount() { if (dimsData==null) return -1; int count = 0; for (DimsData dd : dimsData) { if (!dd.getPlotAxis().hasValue()) count++; } return count; } public int getRangeCount() { int count = 0; for (DimsData dd : dimsData) { if (dd.getPlotAxis()==AxisType.RANGE) count++; } return count; } public boolean is2D() { return getAxisCount()==2; } public DimsDataList clone() { final DimsDataList clone = new DimsDataList(); for (DimsData dd : iterable()) { DimsData dnew = dd.clone(); clone.add(dnew); } clone.expression = expression; return clone; } /** * Sets any axes there are to the axis passed in */ public void normalise(AxisType axis) { for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) dd.setPlotAxis(axis); } } /** * Probably not best algorithm but we are dealing with very small arrays here. * This is simply trying to ensure that only one dimension is selected as an * axis because the plot has changed. * * @param iaxisToFind */ public void setSingleAxisOnly(AxisType iaxisToFind, AxisType iaxisValue) { DimsData found = null; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==iaxisToFind) { dd.setPlotAxis(iaxisValue); found=dd; } } if (found!=null) { for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is x for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) { dd.setPlotAxis(iaxisValue); found=dd; } } for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis */ public void setTwoAxesOnly(AxisType firstAxis, AxisType secondAxis) { boolean foundFirst = false, foundSecond = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; } if (foundFirst&&foundSecond) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis * @param thirdAxis */ public void setThreeAxesOnly(AxisType firstAxis, AxisType secondAxis, AxisType thirdAxis) { boolean foundFirst = false, foundSecond = false, foundThird = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; if (dd.getPlotAxis()==thirdAxis) foundThird = true; } if (foundFirst&&foundSecond&&foundThird) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis, thirdAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis, thirdAxis); if (!foundThird) foundThird = processAxis(thirdAxis, firstAxis, secondAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } private final boolean processAxis(AxisType axis, AxisType... ignoredAxes) { final List ignored = asList(ignoredAxes); for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue() && !ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } for (DimsData dd : iterable()) { if (!ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } return false; } /** * Convert a primitive array to a list. * @param array - an array of primitives * @return */ @SuppressWarnings("unchecked") private static final List asList(final Object array) { if (!array.getClass().isArray()) throw new IllegalArgumentException("Not an array"); return new AbstractList() { @Override public T get(int index) { return (T) Array.get(array, index); } @Override public int size() { return Array.getLength(array); } }; } public boolean isXFirst() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().hasValue()) continue; return dd.getPlotAxis()==AxisType.X; } return false; } public void reverseImage() { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==AxisType.X) { dd.setPlotAxis(AxisType.Y); continue; } if (dd.getPlotAxis()==AxisType.Y) { dd.setPlotAxis(AxisType.X); continue; } } } public boolean isExpression() { return expression; } public void setExpression(boolean expression) { this.expression = expression; } public boolean isEmpty() { return dimsData==null || dimsData.isEmpty(); } public boolean isAdvanced() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().isAdvanced()) return true; } return false; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public List getDimsData() { return dimsData; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public void setDimsData(List dimsData) { this.dimsData = dimsData; } public void removeLargeStacks(ISliceSystem slicingSystem, int maxStack) { for (DimsData dd : getDimsData()) { if (dd.getPlotAxis().isStack(slicingSystem)) { if (dd.getSliceRange(true)==null || "".equals(dd.getSliceRange(true)) || "all".equals(dd.getSliceRange(true))) { final ILazyDataset lz = slicingSystem.getData().getLazySet(); if (lz!=null) { final int size = lz.getShape()[dd.getDimension()]; if (size>=maxStack) { // We set a default slice dd.setSliceRange("0:25"); } } } } } } public Slice[] toSliceArray(int[] dataShape) { final Slice[] ret = new Slice[size()]; for (int i = 0; i < size(); i++) { DimsData dd = getDimsData(i); if (dd.isSlice()) { ret[i] = new Slice(dd.getSlice(), dd.getSlice()+1); } else { ret[i] = new Slice(dataShape[dd.getDimension()]); } } return ret; } /** * Export to Map from DimsDataList * @return */ public Map toMap() { final Map ret = new HashMap(size()); for (DimsData dd : iterable()) { if (dd.isSlice()) { ret.put(dd.getDimension(), String.valueOf(dd.getSlice())); } else if (dd.isTextRange()) { ret.put(dd.getDimension(), dd.getSliceRange()!=null ? dd.getSliceRange() : "all"); } else if ( dd.getPlotAxis()!=null){ ret.put(dd.getDimension(), dd.getPlotAxis().getName()); } } return ret; } /** * Set the current DimsDataList to what is defined in the pass in map. * @param map * @param shape */ public void fromMap(Map map, int[] shape) { clear(); for (int i = 0; i < shape.length; i++) { add(new DimsData(i)); } if (map.isEmpty()) { // Make one up getDimsData(0).setSliceRange("all"); if (size()==2) { getDimsData(1).setPlotAxis(AxisType.X); } else if (size()>2) { getDimsData(1).setPlotAxis(AxisType.Y); getDimsData(2).setPlotAxis(AxisType.X); for (int i = 3; i < size(); i++) { getDimsData(i).setSlice(0); } } } else { // Init one from map saved int dim = 0; for (DimsData dd : iterable()) { String value = map.get(dd.getDimension()); if (value==null) value = map.get(String.valueOf(dd.getDimension())); if (value!=null) { if ("all".equals(value)) { dd.setPlotAxis(AxisType.RANGE); continue; } AxisType at = AxisType.forLabel(value); if (at!=null) { dd.setPlotAxis(at); continue; } try { dd.setSlice(Integer.parseInt(value)); } catch (Exception ne) { dd.setSliceRange(value); } } else { AxisType type = AxisType.forAxis(dim); dd.setPlotAxis(type); ++dim; } } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 652 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.slicing.api/src/org/eclipse/dawnsci/slicing/api/system/DimsDataList.java/#L26-L549 | 2 | 17 | 652 | critical |
| 2294 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13978 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 2294 | 13978 | minor |
| 2200 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13500 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 2 | 2200 | 13500 | minor |
| 213 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2324 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 2 | 213 | 2324 | minor |
| 390 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface CassandraSieveRepositoryModule { CassandraModule MODULE = CassandraModule.builder() .table(CassandraSieveTable.TABLE_NAME) .comment("Holds SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveTable.USER_NAME, text()) .addClusteringColumn(CassandraSieveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveTable.SCRIPT_CONTENT, text()) .addColumn(CassandraSieveTable.IS_ACTIVE, cboolean()) .addColumn(CassandraSieveTable.SIZE, bigint())) .table(CassandraSieveSpaceTable.TABLE_NAME) .comment("Holds per user current space occupied by SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveSpaceTable.USER_NAME, text()) .addColumn(CassandraSieveSpaceTable.SPACE_USED, counter())) .table(CassandraSieveQuotaTable.TABLE_NAME) .comment("Holds per user size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveQuotaTable.USER_NAME, text()) .addColumn(CassandraSieveQuotaTable.QUOTA, bigint())) .table(CassandraSieveClusterQuotaTable.TABLE_NAME) .comment("Holds default size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveClusterQuotaTable.NAME, text()) .addColumn(CassandraSieveClusterQuotaTable.VALUE, bigint())) .table(CassandraSieveActiveTable.TABLE_NAME) .comment("Denormalisation table. Allows per user direct active SIEVE script retrieval.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveActiveTable.USER_NAME, text()) .addColumn(CassandraSieveActiveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveActiveTable.DATE, timestamp())) .build(); } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 3954 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-cassandra/src/main/java/org/apache/james/sieve/cassandra/CassandraSieveRepositoryModule.java/#L35-L74 | 2 | 390 | 3954 | major |
| 236 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JAXRSOutInterceptor extends AbstractOutDatabindingInterceptor { private static final Logger LOG = LogUtils.getL7dLogger(JAXRSOutInterceptor.class); private static final ResourceBundle BUNDLE = BundleUtils.getBundle(JAXRSOutInterceptor.class); public JAXRSOutInterceptor() { super(Phase.MARSHAL); } public void handleMessage(Message message) { ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); try { processResponse(providerFactory, message); } finally { ServerProviderFactory.releaseRequestState(providerFactory, message); } } @SuppressWarnings("resource") // Response shouldn't be closed here private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.isEmpty()) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response)responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class .getName()); serializeMessage(providerFactory, message, response, ori, true); } private int getStatus(Message message, int defaultValue) { Object customStatus = message.getExchange().get(Message.RESPONSE_CODE); return customStatus == null ? defaultValue : (Integer)customStatus; } private void serializeMessage(ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) { ResponseImpl response = (ResponseImpl)JAXRSUtils.copyResponseIfNeeded(theResponse); final Exchange exchange = message.getExchange(); boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod()); Object entity = response.getActualEntity(); if (headResponse && entity != null) { LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString()); entity = null; } Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke(); Annotation[] annotations = null; Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[]{}; Annotation[] responseAnns = response.getEntityAnnotations(); if (responseAnns != null) { annotations = new Annotation[staticAnns.length + responseAnns.length]; System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length); System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length); } else { annotations = staticAnns; } response.setStatus(getActualStatus(response.getStatus(), entity)); response.setEntity(entity, annotations); // Prepare the headers MultivaluedMap responseHeaders = prepareResponseHeaders(message, response, entity, firstTry); // Run the filters try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } // Write the entity entity = InjectionUtils.getEntity(response.getActualEntity()); setResponseStatus(message, getActualStatus(response.getStatus(), entity)); if (entity == null) { if (!headResponse) { responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0"); if (MessageUtils.getContextualBoolean(message, "remove.content.type.for.empty.response", false)) { responseHeaders.remove(HttpHeaders.CONTENT_TYPE); message.remove(Message.CONTENT_TYPE); } } HttpUtils.convertHeaderValuesToString(responseHeaders, true); return; } Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS); boolean ignoreWriters = ignoreWritersProp != null && Boolean.valueOf(ignoreWritersProp.toString()); if (ignoreWriters) { writeResponseToStream(message.getContent(OutputStream.class), entity); return; } MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE)); Class serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null; Class targetType = InjectionUtils.getRawResponseClass(entity); Type genericType = InjectionUtils.getGenericResponseType(invoked, serviceCls, response.getActualEntity(), targetType, exchange); targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType); annotations = response.getEntityAnnotations(); List writers = providerFactory .createMessageBodyWriterInterceptor(targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings()); OutputStream outOriginal = message.getContent(OutputStream.class); if (writers == null || writers.isEmpty()) { writeResponseErrorMessage(message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType); return; } try { boolean checkWriters = false; if (responseMediaType.isWildcardSubtype()) { Produces pM = AnnotationUtils.getMethodAnnotation(ori == null ? null : ori.getAnnotatedMethod(), Produces.class); Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class); checkWriters = pM == null && pC == null; } responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Response content type is: " + finalResponseContentType); } responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType); message.put(Message.CONTENT_TYPE, finalResponseContentType); boolean enabled = checkBufferingMode(message, writers, firstTry); try { try { JAXRSUtils.writeMessageBody(writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message); if (isResponseRedirected(message)) { return; } checkCachedStream(message, outOriginal, enabled); } finally { if (enabled) { OutputStream os = message.getContent(OutputStream.class); if (os != outOriginal && os instanceof CachedOutputStream) { os.close(); } message.setContent(OutputStream.class, outOriginal); message.put(XMLStreamWriter.class.getName(), null); } } } catch (Throwable ex) { logWriteError(firstTry, targetType, responseMediaType); handleWriteException(providerFactory, message, ex, firstTry); } } private MultivaluedMap prepareResponseHeaders(Message message, ResponseImpl response, Object entity, boolean firstTry) { MultivaluedMap responseHeaders = response.getMetadata(); @SuppressWarnings("unchecked") Map> userHeaders = (Map>)message.get(Message.PROTOCOL_HEADERS); if (firstTry && userHeaders != null) { responseHeaders.putAll(userHeaders); } if (entity != null) { Object customContentType = responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE); if (customContentType == null) { String initialResponseContentType = (String)message.get(Message.CONTENT_TYPE); if (initialResponseContentType != null) { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, initialResponseContentType); } } else { message.put(Message.CONTENT_TYPE, customContentType.toString()); } } message.put(Message.PROTOCOL_HEADERS, responseHeaders); setResponseDate(responseHeaders, firstTry); return responseHeaders; } private MediaType getResponseMediaType(Object mediaTypeHeader) { MediaType responseMediaType; if (mediaTypeHeader instanceof MediaType) { responseMediaType = (MediaType)mediaTypeHeader; } else { responseMediaType = mediaTypeHeader == null ? MediaType.WILDCARD_TYPE : JAXRSUtils.toMediaType(mediaTypeHeader.toString()); } return responseMediaType; } private int getActualStatus(int status, Object responseObj) { if (status == -1) { return responseObj == null ? 204 : 200; } return status; } private boolean checkBufferingMode(Message m, List writers, boolean firstTry) { if (!firstTry) { return false; } WriterInterceptor last = writers.get(writers.size() - 1); MessageBodyWriter w = ((WriterInterceptorMBW)last).getMBW(); Object outBuf = m.getContextualProperty(OUT_BUFFERING); boolean enabled = PropertyUtils.isTrue(outBuf); boolean configurableProvider = w instanceof AbstractConfigurableProvider; if (!enabled && outBuf == null && configurableProvider) { enabled = ((AbstractConfigurableProvider)w).getEnableBuffering(); } if (enabled) { boolean streamingOn = configurableProvider && ((AbstractConfigurableProvider)w).getEnableStreaming(); if (streamingOn) { m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter()); } else { m.setContent(OutputStream.class, new CachedOutputStream()); } } return enabled; } private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled) throws Exception { XMLStreamWriter writer = null; if (enabled) { writer = m.getContent(XMLStreamWriter.class); } else { writer = (XMLStreamWriter)m.get(XMLStreamWriter.class.getName()); } if (writer instanceof CachingXmlEventWriter) { CachingXmlEventWriter cache = (CachingXmlEventWriter)writer; if (cache.getEvents().size() != 0) { XMLStreamWriter origWriter = null; try { origWriter = StaxUtils.createXMLStreamWriter(osOriginal); for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origWriter); } } finally { StaxUtils.close(origWriter); } } m.setContent(XMLStreamWriter.class, null); return; } if (enabled) { OutputStream os = m.getContent(OutputStream.class); if (os != osOriginal && os instanceof CachedOutputStream) { CachedOutputStream cos = (CachedOutputStream)os; if (cos.size() != 0) { cos.writeCacheTo(osOriginal); } } } } private void logWriteError(boolean firstTry, Class cls, MediaType ct) { if (firstTry) { JAXRSUtils.logMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, ct); } } private void handleWriteException(ServerProviderFactory pf, Message message, Throwable ex, boolean firstTry) { Response excResponse = null; if (firstTry) { excResponse = JAXRSUtils.convertFaultToResponse(ex, message); } else { message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE); } if (excResponse == null) { setResponseStatus(message, 500); throw new Fault(ex); } serializeMessage(pf, message, excResponse, null, false); } private void writeResponseErrorMessage(Message message, OutputStream out, String name, Class cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } } private MediaType checkFinalContentType(MediaType mt, List writers, boolean checkWriters) { if (checkWriters) { int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1; MessageBodyWriter writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW(); Produces pm = writer.getClass().getAnnotation(Produces.class); if (pm != null) { List sorted = JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM); mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0); } } if (mt.isWildcardType() || mt.isWildcardSubtype()) { if ("application".equals(mt.getType()) || mt.isWildcardType()) { mt = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { throw ExceptionUtils.toNotAcceptableException(null, null); } } return mt; } private void setResponseDate(MultivaluedMap headers, boolean firstTry) { if (!firstTry || headers.containsKey(HttpHeaders.DATE)) { return; } SimpleDateFormat format = HttpUtils.getHttpDateFormat(); headers.putSingle(HttpHeaders.DATE, format.format(new Date())); } private boolean isResponseAlreadyHandled(Message m) { return isResponseAlreadyCommited(m) || isResponseRedirected(m); } private boolean isResponseAlreadyCommited(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.RESPONSE_COMMITED)); } private boolean isResponseRedirected(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.REQUEST_REDIRECTED)); } private void writeResponseToStream(OutputStream os, Object responseObj) { try { byte[] bytes = responseObj.toString().getBytes(StandardCharsets.UTF_8); os.write(bytes, 0, bytes.length); } catch (Exception ex) { LOG.severe("Problem with writing the data to the output stream"); ex.printStackTrace(); throw new RuntimeException(ex); } } private void setResponseStatus(Message message, int status) { message.put(Message.RESPONSE_CODE, status); boolean responseHeadersCopied = isResponseHeadersCopied(message); if (responseHeadersCopied) { HttpServletResponse response = (HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE); response.setStatus(status); } } // Some CXF interceptors such as FIStaxOutInterceptor will indirectly initiate // an early copying of response code and headers into the HttpServletResponse // TODO : Pushing the filter processing and copying response headers into say // PRE-LOGICAl and PREPARE_SEND interceptors will most likely be a good thing // however JAX-RS MessageBodyWriters are also allowed to add response headers // which is reason why a MultipartMap parameter in MessageBodyWriter.writeTo // method is modifiable. Thus we do need to know if the initial copy has already // occurred: for now we will just use to ensure the correct status is set private boolean isResponseHeadersCopied(Message message) { return PropertyUtils.isTrue(message.get(AbstractHTTPDestination.RESPONSE_HEADERS_COPIED)); } public void handleFault(Message message) { // complete } } |
blob | feature envy | t | t | f | feature envy | blob | 0 | 2557 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java/#L73-L495 | 1 | 236 | 2557 | critical |
| 1646 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11562 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1646 | 11562 | minor |
| 837 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 7771 | https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 | 1 | 837 | 7771 | minor |
| 1539 | { "output": "YES I found bad smells the bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private final class SymbolProcessor implements FunctionVisitor, InstructionVisitorAdapter { private final SourceFunction function; private final LinkedList removeFromBlock = new LinkedList<>(); private int blockInstIndex = 0; private DbgValueInstruction lastDbgValue = null; private InstructionBlock currentBlock = null; private SymbolProcessor(SourceFunction function) { this.function = function; } @Override public void visit(InstructionBlock block) { currentBlock = block; lastDbgValue = null; for (blockInstIndex = 0; blockInstIndex < block.getInstructionCount(); blockInstIndex++) { block.getInstruction(blockInstIndex).accept(this); } if (!removeFromBlock.isEmpty()) { for (int i : removeFromBlock) { currentBlock.remove(i); } removeFromBlock.clear(); } } @Override public void visitInstruction(Instruction instruction) { final MDLocation loc = instruction.getDebugLocation(); if (loc != null) { final LLVMSourceLocation scope = cache.buildLocation(loc); if (scope != null) { instruction.setSourceLocation(scope); } } } @Override public void visit(VoidCallInstruction call) { final SymbolImpl callTarget = call.getCallTarget(); if (callTarget instanceof FunctionDeclaration) { switch (((FunctionDeclaration) callTarget).getName()) { case LLVM_DBG_DECLARE_NAME: handleDebugIntrinsic(call, true); return; case LLVM_DBG_ADDR_NAME: // dbg.declare and dbg.addr have the same interface and, for our purposes, // the same semantics handleDebugIntrinsic(call, true); return; case LLVM_DBG_VALUE_NAME: handleDebugIntrinsic(call, false); return; case LLVM_DEBUGTRAP_NAME: visitDebugTrap(call); return; } } visitInstruction(call); } private void visitDebugTrap(VoidCallInstruction call) { final DebugTrapInstruction trap = DebugTrapInstruction.create(call); currentBlock.set(blockInstIndex, trap); visitInstruction(trap); } private SourceVariable getVariable(VoidCallInstruction call, int index) { final SymbolImpl varSymbol = getArg(call, index); if (varSymbol instanceof MetadataSymbol) { final MDBaseNode mdLocal = ((MetadataSymbol) varSymbol).getNode(); final LLVMSourceSymbol symbol = cache.getSourceSymbol(mdLocal, false); return function.getLocal(symbol); } return null; } private void handleDebugIntrinsic(VoidCallInstruction call, boolean isDeclaration) { SymbolImpl value = getArg(call, LLVM_DBG_INTRINSICS_VALUE_ARGINDEX); if (value instanceof MetadataSymbol) { value = MDSymbolExtractor.getSymbol(((MetadataSymbol) value).getNode()); } if (value == null) { // this may happen if llvm optimizations removed a variable value = new NullConstant(MetaType.DEBUG); } else if (value instanceof ValueInstruction) { ((ValueInstruction) value).setSourceVariable(true); } else if (value instanceof FunctionParameter) { ((FunctionParameter) value).setSourceVariable(true); } int mdLocalArgIndex; int mdExprArgIndex; if (isDeclaration) { mdLocalArgIndex = LLVM_DBG_DECLARE_LOCALREF_ARGINDEX; mdExprArgIndex = LLVM_DBG_DECLARE_EXPR_ARGINDEX; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_NEW) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_NEW; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_NEW; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_OLD; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_OLD; } else { return; } final SourceVariable variable = getVariable(call, mdLocalArgIndex); if (variable == null) { // invalid or unsupported debug information // remove upper indices so we do not need to update the later ones removeFromBlock.addFirst(blockInstIndex); return; } final MDExpression expression = getExpression(call, mdExprArgIndex); if (ValueFragment.describesFragment(expression)) { variable.addFragment(ValueFragment.parse(expression)); } else { variable.addFullDefinition(); } if (isDeclaration) { final DbgDeclareInstruction dbgDeclare = new DbgDeclareInstruction(value, variable, expression); variable.addDeclaration(dbgDeclare); currentBlock.set(blockInstIndex, dbgDeclare); } else { long index = 0; if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { final SymbolImpl indexSymbol = call.getArgument(LLVM_DBG_VALUE_INDEX_ARGINDEX_OLD); final Long l = LLVMSymbolReadResolver.evaluateLongIntegerConstant(indexSymbol); if (l != null) { index = l; } } final DbgValueInstruction dbgValue = new DbgValueInstruction(value, variable, index, expression); if (dbgValue.equals(lastDbgValue)) { // at higher optimization levels llvm often duplicates the @llvm.dbg.value // intrinsic call, we remove it again to avoid unnecessary runtime overhead removeFromBlock.addFirst(blockInstIndex); } else { variable.addValue(dbgValue); currentBlock.set(blockInstIndex, dbgValue); lastDbgValue = dbgValue; } } } } |
blob | t | f | f | blob | 0 | 11229 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/sulong/projects/com.oracle.truffle.llvm.parser/src/com/oracle/truffle/llvm/parser/metadata/debuginfo/DebugInfoFunctionProcessor.java/#L145-L308 | 1 | 1539 | 11229 | major | ||
| 2619 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 15051 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 1 | 2619 | 15051 | minor |
| 1772 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11921 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 1 | 1772 | 11921 | minor |
| 652 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6386 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 652 | 6386 | critical |
| 4546 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12082 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 1 | 4546 | 12082 | minor |
| 3117 | {"YES I found bad smells":[ "Data Class" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JpaEntityFactoryMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String INDEX_VAR = "index"; private static final JavaSymbolName INDEX_SYMBOL = new JavaSymbolName(INDEX_VAR); private static final JavaSymbolName MAX_SYMBOL = new JavaSymbolName("max"); private static final JavaSymbolName MIN_SYMBOL = new JavaSymbolName("min"); private static final String OBJ_VAR = "obj"; private static final JavaSymbolName OBJ_SYMBOL = new JavaSymbolName(OBJ_VAR); private static final JavaSymbolName VALUE = new JavaSymbolName("value"); private static final JavaSymbolName CREATE_FACTORY_METHOD_NAME = new JavaSymbolName("create"); public static final JavaSymbolName SPECIFIC_METHOD_PREFIX = new JavaSymbolName("getSpecific"); private static final String PROVIDES_TYPE_STRING = JpaEntityFactoryMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); public static String createIdentifier(final JavaType javaType, final LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static String createIdentifier(ClassOrInterfaceTypeDetails details) { final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(details.getDeclaredByMetadataId()); return createIdentifier(details.getType(), logicalPath); } public static JavaType getJavaType(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static LogicalPath getPath(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private JavaType entity; private final List requiredDataOnDemandCollaborators = new ArrayList(); private MethodMetadata randomPersistentEntityMethod; private final Map> embeddedFieldInitializers = new LinkedHashMap>(); private final Map fieldInitializers = new LinkedHashMap(); private EmbeddedIdHolder embeddedIdHolder; private List embeddedHolders; private Map locatedFields; private final MemberDetails entityMemberDetails; /** * Constructor * * @param identifier * @param aspectName * @param governorPhysicalTypeMetadata * @param entity * @param entityMemberDetails * @param locatedFields * @param embeddedHolder * @param entityFactoryClasses * @param embeddedIdHolder */ public JpaEntityFactoryMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JavaType entity, MemberDetails entityMemberDetails, final Map locatedFields, final List embeddedHolders, Set entityFactoryClasses, final EmbeddedIdHolder embeddedIdHolder) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.notNull(locatedFields, "Located fields map required"); Validate.notNull(embeddedHolders, "Embedded holders list required"); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.embeddedIdHolder = embeddedIdHolder; this.embeddedHolders = embeddedHolders; this.locatedFields = locatedFields; builder.addMethod(getCreateMethod()); // Calculate and store field initializers for (final Map.Entry entry : locatedFields.entrySet()) { final FieldMetadata field = entry.getKey(); final String initializer = getFieldInitializer(field, entry.getValue(), entityFactoryClasses); if (!StringUtils.isBlank(initializer)) { this.fieldInitializers.put(field, initializer); } } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { final Map initializers = new LinkedHashMap(); for (final FieldMetadata field : embeddedHolder.getFields()) { initializers.put(field, getFieldInitializer(field, null, entityFactoryClasses)); } this.embeddedFieldInitializers.put(embeddedHolder.getEmbeddedField(), initializers); } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { builder.addMethod(getEmbeddedClassMutatorMethod(embeddedHolder)); addEmbeddedClassFieldMutatorMethodsToBuilder(embeddedHolder, entityFactoryClasses); } for (final MethodMetadataBuilder fieldInitializerMethod : getFieldMutatorMethods()) { builder.addMethod(fieldInitializerMethod); } addCollaboratingFieldsToBuilder(entityFactoryClasses); builder.addMethod(getEmbeddedIdMutatorMethod(entityFactoryClasses)); itdTypeDetails = builder.build(); } private void addCollaboratingFieldsToBuilder( final Set entityFactoryClasses) { final Set fields = new LinkedHashSet(); for (final JavaType entityNeedingCollaborator : this.requiredDataOnDemandCollaborators) { final JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator, entityFactoryClasses); if (collaboratorType != null) { final String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator, entityFactoryClasses) .getSymbolName(); final JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // We really expect the field to be correct if we're going to // rely on it Validate .isTrue(candidate.getFieldType().equals(collaboratorType), "Field '%s' on '%s' must be of type '%s'", collaboratingFieldName, destination.getFullyQualifiedTypeName(), collaboratorType.getFullyQualifiedTypeName()); Validate.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '%s' on '%s' must be private", collaboratingFieldName, destination.getFullyQualifiedTypeName()); Validate.notNull( MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), AUTOWIRED), "Field '%s' on '%s' must be @Autowired", collaboratingFieldName, destination.getFullyQualifiedTypeName()); // It's ok, so we can move onto the new field continue; } // Create field and add it to the ITD, if it hasn't already been if (!fields.contains(fieldSymbolName)) { // Must make the field final List annotations = new ArrayList(); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); builder.addField(new FieldMetadataBuilder(getId(), 0, annotations, fieldSymbolName, collaboratorType)); fields.add(fieldSymbolName); } } } } private void addEmbeddedClassFieldMutatorMethodsToBuilder(final EmbeddedHolder embeddedHolder, final Set dataOnDemandClasses) { final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); final JavaType[] parameterTypes = {embeddedFieldType, JavaType.INT_PRIMITIVE}; final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); for (final FieldMetadata field : embeddedHolder.getFields()) { final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); final JavaSymbolName fieldMutatorMethodName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, fieldMutatorMethodName, false)); final JavaSymbolName embeddedClassMethodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()); if (governorHasMethod(embeddedClassMethodName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } builder.addMethod(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, embeddedClassMethodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType .convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } private String getColumnPrecisionAndScaleBody(final FieldMetadata field, final Map values, final String suffix) { if (values == null || !values.containsKey("precision")) { return InvocableMemberBodyBuilder.getInstance().getOutput(); } final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); Integer precision = (Integer) values.get("precision"); Integer scale = (Integer) values.get("scale"); if (precision != null && scale != null && precision < scale) { scale = 0; } final BigDecimal maxValue; if (scale == null || scale == 0) { maxValue = new BigDecimal(StringUtils.rightPad("9", precision, '9')); } else { maxValue = new BigDecimal(StringUtils.rightPad("9", precision - scale, '9') + "." + StringUtils.rightPad("9", scale, '9')); } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private JavaSymbolName getCollaboratingFieldName(final JavaType entity, final Set dataOnDemandClasses) { JavaSymbolName symbolName = null; JavaType collaboratingType = getCollaboratingType(entity, dataOnDemandClasses); if (collaboratingType != null) { symbolName = new JavaSymbolName(StringUtils.uncapitalize(collaboratingType.getSimpleTypeName())); } return symbolName; } private JavaType getCollaboratingType(final JavaType entity, final Set entityFactoryClasses) { JavaType dataOnDemand = null; for (ClassOrInterfaceTypeDetails dataOnDemandClass : entityFactoryClasses) { String searchDataOnDemand = entity.getSimpleTypeName().concat("DataOnDemand"); if (dataOnDemandClass.getType().getSimpleTypeName().equals(searchDataOnDemand) && governorTypeDetails.getType().getModule() .equals(dataOnDemandClass.getType().getModule())) { dataOnDemand = dataOnDemandClass.getType(); } } return dataOnDemand; } private MethodMetadata getCreateMethod() { // Define methodName final JavaSymbolName methodName = CREATE_FACTORY_METHOD_NAME; List parameterTypes = new ArrayList(); parameterTypes.add(JavaType.INT_PRIMITIVE); // Check if method exists MethodMetadata existingMethod = getGovernorMethod(methodName, parameterTypes); if (existingMethod != null) { return existingMethod; } List parameterNames = new ArrayList(); parameterNames.add(INDEX_SYMBOL); // Add body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); List constructors = entityMemberDetails.getConstructors(); boolean hasDefaultConstructor = false; for (ConstructorMetadata constructor : constructors) { if (constructor.getParameterTypes().isEmpty() && Modifier.isPublic(constructor.getModifier())) { hasDefaultConstructor = true; break; } } if (constructors.isEmpty() || hasDefaultConstructor) { generateDefaultCreateMethodBody(bodyBuilder); } else { generateNoConstructorCreateMethodBody(bodyBuilder); } // Create method MethodMetadataBuilder method = new MethodMetadataBuilder(this.getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); CommentStructure commentStructure = new CommentStructure(); List paramsInfo = new ArrayList(); paramsInfo.add(String.format("%s position of the %s", INDEX_VAR, this.entity.getSimpleTypeName())); JavadocComment comment = new JavadocComment(String.format("Creates a new {@link %s} with the given %s.", this.entity.getSimpleTypeName(), INDEX_VAR), paramsInfo, String.format( "a new transient %s", this.entity.getSimpleTypeName()), null); commentStructure.addComment(comment, CommentLocation.BEGINNING); method.setCommentStructure(commentStructure); return method.build(); } /** * Generate default body for create method * * @param bodyBuilder */ private void generateDefaultCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // Entity obj = new Entity(); bodyBuilder.appendFormalLine("%1$s %2$s = new %1$s();", getNameOfJavaType(this.entity), OBJ_SYMBOL); // Set values for transient object for (final Map.Entry entry : locatedFields.entrySet()) { bodyBuilder.appendFormalLine("%s(%s, %s);", BeanInfoUtils.getMutatorMethodName(entry.getKey()), OBJ_SYMBOL, INDEX_SYMBOL); } // return obj; bodyBuilder.appendFormalLine("return %s;", OBJ_SYMBOL); } /** * Generate body for create method when entity has not default constructor available * * @param bodyBuilder */ private void generateNoConstructorCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // throw new IllegalStateException("No no-argument constructor found for the entity "+ Pet.class.getName() +". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again."); bodyBuilder .appendFormalLine( "throw new IllegalStateException(\"No no-argument constructor found for the entity \"+ %s.class.getName() +\". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again.\");", getNameOfJavaType(this.entity)); } private String getDecimalMinAndDecimalMaxBody(final FieldMetadata field, final AnnotationMetadata decimalMinAnnotation, final AnnotationMetadata decimalMaxAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (decimalMinAnnotation != null && decimalMaxAnnotation == null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation == null && decimalMaxAnnotation != null) { final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation != null && decimalMaxAnnotation != null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue( Double.parseDouble(maxValue) >= Double.parseDouble(minValue), "The value of @DecimalMax must be greater or equal to the value of @DecimalMin for field %s", fieldName); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getDigitsBody(final FieldMetadata field, final AnnotationMetadata digitsAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final Integer integerValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("integer")).getValue(); final Integer fractionValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("fraction")).getValue(); final BigDecimal maxValue = new BigDecimal(StringUtils.rightPad("9", integerValue, '9') + "." + StringUtils.rightPad("9", fractionValue, '9')); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private String getFieldInitializer(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set dataOnDemandClasses) { final JavaType fieldType = field.getFieldType(); final String fieldName = field.getFieldName().getSymbolName(); String initializer = "null"; final String fieldInitializer = field.getFieldInitializer(); final Set fieldCustomDataKeys = field.getCustomData().keySet(); // Date fields included for DataNucleus ( if (fieldType.equals(DATE)) { if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() - 10000000L)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() + 10000000L)"; } else { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); initializer = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime()"; } } else if (fieldType.equals(CALENDAR)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); final String calendarString = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH)"; if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { initializer = calendarString + " - 1)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { initializer = calendarString + " + 1)"; } else { initializer = "Calendar.getInstance()"; } } else if (fieldType.equals(TIMESTAMP)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR, TIMESTAMP); initializer = "new Timestamp(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime().getTime())"; } else if (fieldType.equals(STRING)) { if (fieldInitializer != null && fieldInitializer.contains("\"")) { final int offset = fieldInitializer.indexOf("\""); initializer = fieldInitializer.substring(offset + 1, fieldInitializer.lastIndexOf("\"")); } else { initializer = fieldName; } if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), VALIDATOR_CONSTRAINTS_EMAIL) != null || fieldName.toLowerCase().contains("email")) { initializer = "\"foo\" + " + INDEX_VAR + " + \"@bar.com\""; } else { int maxLength = Integer.MAX_VALUE; // Check for @Size final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null) { final AnnotationAttributeValue maxValue = sizeAnnotation.getAttribute(MAX_SYMBOL); if (maxValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "max", maxValue.getValue()); maxLength = ((Integer) maxValue.getValue()).intValue(); } final AnnotationAttributeValue minValue = sizeAnnotation.getAttribute(MIN_SYMBOL); if (minValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "min", minValue.getValue()); final int minLength = ((Integer) minValue.getValue()).intValue(); Validate.isTrue(maxLength >= minLength, "@Size attribute 'max' must be greater than 'min' for field '%s' in %s", fieldName, entity.getFullyQualifiedTypeName()); if (initializer.length() + 2 < minLength) { initializer = String.format("%1$-" + (minLength - 2) + "s", initializer).replace(' ', 'x'); } } } else { if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map columnValues = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (columnValues.keySet().contains("length")) { final Object lengthValue = columnValues.get("length"); validateNumericAnnotationAttribute(fieldName, "@Column", "length", lengthValue); maxLength = ((Integer) lengthValue).intValue(); } } } switch (maxLength) { case 0: initializer = "\"\""; break; case 1: initializer = "String.valueOf(" + INDEX_VAR + ")"; break; case 2: initializer = "\"" + initializer.charAt(0) + "\" + " + INDEX_VAR; break; default: if (initializer.length() + 2 > maxLength) { initializer = "\"" + initializer.substring(0, maxLength - 2) + "_\" + " + INDEX_VAR; } else { initializer = "\"" + initializer + "_\" + " + INDEX_VAR; } } } } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ \"Y\", \"N\" }"); } else if (fieldType.equals(JavaType.BOOLEAN_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "Boolean.TRUE"); } else if (fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "true"); } else if (fieldType.equals(JavaType.INT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ")"); } else if (fieldType.equals(JavaType.INT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, INDEX_VAR); } else if (fieldType.equals(new JavaType(JavaType.INT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ " + INDEX_VAR + ", " + INDEX_VAR + " }"); } else if (fieldType.equals(JavaType.DOUBLE_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); } else if (fieldType.equals(new JavaType(JavaType.DOUBLE_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").doubleValue(), new Integer(" + INDEX_VAR + ").doubleValue() }"); } else if (fieldType.equals(JavaType.FLOAT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); } else if (fieldType.equals(new JavaType(JavaType.FLOAT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").floatValue(), new Integer(" + INDEX_VAR + ").floatValue() }"); } else if (fieldType.equals(JavaType.LONG_OBJECT)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.LONG_PRIMITIVE)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); } else if (fieldType.equals(new JavaType(JavaType.LONG_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").longValue(), new Integer(" + INDEX_VAR + ").longValue() }"); } else if (fieldType.equals(JavaType.SHORT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.SHORT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); } else if (fieldType.equals(new JavaType(JavaType.SHORT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").shortValue(), new Integer(" + INDEX_VAR + ").shortValue() }"); } else if (fieldType.equals(JavaType.CHAR_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Character('N')"); } else if (fieldType.equals(JavaType.CHAR_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "'N'"); } else if (fieldType.equals(new JavaType(JavaType.CHAR_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ 'Y', 'N' }"); } else if (fieldType.equals(BIG_DECIMAL)) { builder.getImportRegistrationResolver().addImport(BIG_DECIMAL); initializer = BIG_DECIMAL.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(BIG_INTEGER)) { builder.getImportRegistrationResolver().addImport(BIG_INTEGER); initializer = BIG_INTEGER.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(JavaType.BYTE_OBJECT)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ")"; } else if (fieldType.equals(JavaType.BYTE_PRIMITIVE)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ").byteValue()"; } else if (fieldType.equals(JavaType.BYTE_ARRAY_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "String.valueOf(" + INDEX_VAR + ").getBytes()"); } else if (fieldType.equals(entity)) { // Avoid circular references (ROO-562) initializer = OBJ_VAR; } else if (fieldCustomDataKeys.contains(CustomDataKeys.ENUMERATED_FIELD)) { builder.getImportRegistrationResolver().addImport(fieldType); initializer = fieldType.getSimpleTypeName() + ".class.getEnumConstants()[0]"; } else if (collaboratingMetadata != null && collaboratingMetadata.getEntityType() != null) { requiredDataOnDemandCollaborators.add(fieldType); initializer = getFieldInitializerForRelatedEntity(field, collaboratingMetadata, fieldCustomDataKeys, dataOnDemandClasses); } return initializer; } private String getFieldInitializerForRelatedEntity(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set fieldCustomDataKeys, final Set dataOnDemandClasses) { // To avoid circular references, we don't try to set nullable fields final boolean nullableField = field.getAnnotation(NOT_NULL) == null && isNullableJoinColumn(field); if (nullableField) { return null; } JavaSymbolName collaboratingFieldName = getCollaboratingFieldName(field.getFieldType(), dataOnDemandClasses); if (collaboratingFieldName != null) { final String collaboratingName = collaboratingFieldName.getSymbolName(); if (fieldCustomDataKeys.contains(CustomDataKeys.ONE_TO_ONE_FIELD)) { // We try to keep the same ID (ROO-568) return collaboratingName + "." + SPECIFIC_METHOD_PREFIX.getSymbolName() + "(" + INDEX_VAR + ")"; } return collaboratingName + "." + collaboratingMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()"; } else { return null; } } private List getFieldMutatorMethods() { final List fieldMutatorMethods = new ArrayList(); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; for (final Map.Entry entry : fieldInitializers.entrySet()) { final FieldMetadata field = entry.getKey(); final JavaSymbolName mutatorName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); // Locate user-defined method if (governorHasMethod(mutatorName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } // Method not on governor so need to create it final String initializer = entry.getValue(); if (!StringUtils.isBlank(initializer)) { final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, mutatorName, false)); fieldMutatorMethods.add(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, mutatorName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } return fieldMutatorMethods; } private String getFieldValidationBody(final FieldMetadata field, final String initializer, final JavaSymbolName mutatorName, final boolean isFieldOfEmbeddableType) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); String suffix = ""; if (fieldType.equals(JavaType.LONG_OBJECT) || fieldType.equals(JavaType.LONG_PRIMITIVE)) { suffix = "L"; } else if (fieldType.equals(JavaType.FLOAT_OBJECT) || fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { suffix = "F"; } else if (fieldType.equals(JavaType.DOUBLE_OBJECT) || fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { suffix = "D"; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(getTypeStr(fieldType) + " " + fieldName + " = " + initializer + ";"); if (fieldType.equals(JavaType.STRING)) { boolean isUnique = isFieldOfEmbeddableType; @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (!isUnique && values != null && values.containsKey("unique")) { isUnique = (Boolean) values.get("unique"); } // Check for @Size or @Column with length attribute final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null && sizeAnnotation.getAttribute(MAX_SYMBOL) != null) { final Integer maxValue = (Integer) sizeAnnotation.getAttribute(MAX_SYMBOL).getValue(); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + maxValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + maxValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + maxValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (sizeAnnotation == null && values != null) { if (values.containsKey("length")) { final Integer lengthValue = (Integer) values.get("length"); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + lengthValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + lengthValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + lengthValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } else if (JdkJavaType.isDecimalType(fieldType)) { // Check for @Digits, @DecimalMax, @DecimalMin final AnnotationMetadata digitsAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DIGITS); final AnnotationMetadata decimalMinAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MIN); final AnnotationMetadata decimalMaxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MAX); if (digitsAnnotation != null) { bodyBuilder.append(getDigitsBody(field, digitsAnnotation, suffix)); } else if (decimalMinAnnotation != null || decimalMaxAnnotation != null) { bodyBuilder.append(getDecimalMinAndDecimalMaxBody(field, decimalMinAnnotation, decimalMaxAnnotation, suffix)); } else if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); bodyBuilder.append(getColumnPrecisionAndScaleBody(field, values, suffix)); } } else if (JdkJavaType.isIntegerType(fieldType)) { // Check for @Min and @Max bodyBuilder.append(getMinAndMaxBody(field, suffix)); } if (mutatorName != null) { bodyBuilder.appendFormalLine(OBJ_VAR + "." + mutatorName.getSymbolName() + "(" + fieldName + ");"); } return bodyBuilder.getOutput(); } private MethodMetadataBuilder getEmbeddedClassMutatorMethod(final EmbeddedHolder embeddedHolder) { final JavaSymbolName methodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName()); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded class final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedFieldType); bodyBuilder.appendFormalLine(embeddedFieldType.getSimpleTypeName() + " embeddedClass = new " + embeddedFieldType.getSimpleTypeName() + "();"); for (final FieldMetadata field : embeddedHolder.getFields()) { bodyBuilder.appendFormalLine(getEmbeddedFieldMutatorMethodName( embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()).getSymbolName() + "(embeddedClass, " + INDEX_VAR + ");"); } bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedHolder.getEmbeddedMutatorMethodName() + "(embeddedClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private MethodMetadataBuilder getEmbeddedIdMutatorMethod( final Set dataOnDemandClasses) { if (!hasEmbeddedIdentifier()) { return null; } final JavaSymbolName embeddedIdMutator = embeddedIdHolder.getEmbeddedIdMutator(); final JavaSymbolName methodName = getEmbeddedIdMutatorMethodName(); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded id class final JavaType embeddedIdFieldType = embeddedIdHolder.getEmbeddedIdField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedIdFieldType); final StringBuilder sb = new StringBuilder(); final List identifierFields = embeddedIdHolder.getIdFields(); for (int i = 0, n = identifierFields.size(); i < n; i++) { if (i > 0) { sb.append(", "); } final FieldMetadata field = identifierFields.get(i); final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); builder.getImportRegistrationResolver().addImport(fieldType); final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); bodyBuilder.append(getFieldValidationBody(field, initializer, null, true)); sb.append(fieldName); } bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine(embeddedIdFieldType.getSimpleTypeName() + " embeddedIdClass = new " + embeddedIdFieldType.getSimpleTypeName() + "(" + sb.toString() + ");"); bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedIdMutator + "(embeddedIdClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private String getMinAndMaxBody(final FieldMetadata field, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); final AnnotationMetadata minAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN); final AnnotationMetadata maxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX); if (minAnnotation != null && maxAnnotation == null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation == null && maxAnnotation != null) { final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation != null && maxAnnotation != null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue(maxValue.longValue() >= minValue.longValue(), "The value of @Max must be greater or equal to the value of @Min for field %s", fieldName); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getTypeStr(final JavaType fieldType) { builder.getImportRegistrationResolver().addImport(fieldType); final String arrayStr = fieldType.isArray() ? "[]" : ""; String typeStr = fieldType.getSimpleTypeName(); if (fieldType.getFullyQualifiedTypeName().equals( JavaType.FLOAT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "float" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.DOUBLE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "double" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.INT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "int" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.SHORT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "short" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.BYTE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "byte" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.CHAR_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "char" + arrayStr; } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { typeStr = "String[]"; } return typeStr; } private boolean isNullableJoinColumn(final FieldMetadata field) { final AnnotationMetadata joinColumnAnnotation = field.getAnnotation(JOIN_COLUMN); if (joinColumnAnnotation == null) { return true; } final AnnotationAttributeValue nullableAttr = joinColumnAnnotation.getAttribute(new JavaSymbolName("nullable")); return nullableAttr == null || (Boolean) nullableAttr.getValue(); } private void validateNumericAnnotationAttribute(final String fieldName, final String annotationName, final String attributeName, final Object object) { Validate.isTrue(NumberUtils.isNumber(object.toString()), "%s '%s' attribute for field '%s' in backing type %s must be numeric", annotationName, attributeName, fieldName, entity.getFullyQualifiedTypeName()); } public JavaSymbolName getCreateFactoryMethodName() { return JpaEntityFactoryMetadata.CREATE_FACTORY_METHOD_NAME; } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName fieldName) { return BeanInfoUtils.getMutatorMethodName(fieldName); } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName embeddedFieldName, final JavaSymbolName fieldName) { return getEmbeddedFieldMutatorMethodName(new JavaSymbolName(embeddedFieldName.getSymbolName() + StringUtils.capitalize(fieldName.getSymbolName()))); } public List getEmbeddedHolders() { return this.embeddedHolders; } public JavaSymbolName getEmbeddedIdMutatorMethodName() { final List fieldNames = new ArrayList(); for (final FieldMetadata field : fieldInitializers.keySet()) { fieldNames.add(field.getFieldName()); } int index = -1; JavaSymbolName embeddedIdField; while (true) { // Compute the required field name index++; embeddedIdField = new JavaSymbolName("embeddedIdClass" + StringUtils.repeat("_", index)); if (!fieldNames.contains(embeddedIdField)) { // Found a usable name break; } } return BeanInfoUtils.getMutatorMethodName(embeddedIdField); } public JavaType getEntityType() { return this.entity; } /** * Returns the {@link JavaType} representing the physical type of this ITD governor. * * @return the {@link JavaType} for the governor physical type. */ public JavaType getGovernorType() { return this.governorPhysicalTypeMetadata.getType(); } /** * @return the "getRandomEntity():Entity" method (never returns null) */ public MethodMetadata getRandomPersistentEntityMethod() { return randomPersistentEntityMethod; } public boolean hasEmbeddedIdentifier() { return this.embeddedIdHolder != null; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } } |
blob | Not specified | f | f | f | [ "Data Class"]} | false | 0 | 4137 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadata.java/#L77-L1176 | 1 | 3117 | 4137 | major |
| 2028 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12806 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 2028 | 12806 | major |
| 2407 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 14389 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 2407 | 14389 | minor |
| 4293 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11322 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 2 | 4293 | 11322 | minor | ||
| 2410 | YES I found bad smells the bad smells are: 1. Duplicate code (repetitive code blocks in multiple methods) 2. Long method (createDocument method is lengthy and performs multiple tasks) 3. Feature envy (getTypeSystemId method is accessing data from the CorpusServerCasEditorInput class, indicating a potential design flaw) 4. Inconsistent naming conventions for variables (tsDesciptor and tsPreferenceStores are misspelled) 5. Lack of proper exception handling (catching and handling all exceptions with the same printStackTrace() method) 6. Tight coupling (the DefaultCasDocumentProvider class is extending a specific implementation of a CasDocumentProvider, leading to a lack of flexibility and potential issues if the superclass is modified) 7. Use of primitive types instead of constants (the value 30000 is hard-coded instead of being defined as a constant) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | Duplicate code (repetitive code blocks in multiple methods)2 Long method (createDocument method is lengthy and performs multiple tasks)3 Feature envy (getTypeSystemId method is accessing data from the CorpusServerCasEditorInput class, indicating a potential design flaw)4 Inconsistent naming conventions for variables (tsDesciptor and tsPreferenceStores are misspelled)5 Lack of proper exception handling (catching and handling all exceptions with the same printStackTrace() method)6 Tight coupling (the DefaultCasDocumentProvider class is extending a specific implementation of a CasDocumentProvider, leading to a lack of flexibility and potential issues if the superclass is modified)7 Use of primitive types instead of constants (the value 30000 is hard-coded instead of being defined as a constant) | t | f | f | . Duplicate code (repetitive code blocks in multiple methods)2. Long method (createDocument method is lengthy and performs multiple tasks)3. Feature envy (getTypeSystemId method is accessing data from the CorpusServerCasEditorInput class, indicating a potential design flaw)4. Inconsistent naming conventions for variables (tsDesciptor and tsPreferenceStores are misspelled)5. Lack of proper exception handling (catching and handling all exceptions with the same printStackTrace() method)6. Tight coupling (the DefaultCasDocumentProvider class is extending a specific implementation of a CasDocumentProvider, leading to a lack of flexibility and potential issues if the superclass is modified)7. Use of primitive types instead of constants (the value 30000 is hard-coded instead of being defined as a constant) | blob | 0 | 14393 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 2 | 2410 | 14393 | major |
| 1596 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11413 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 1596 | 11413 | major |
| 159 | {"message": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class AssignmentTask implements Runnable { final Map> assignmentFailures; HostAndPort location; private Map> assignmentsPerTablet; public AssignmentTask(Map> assignmentFailures, String location, Map> assignmentsPerTablet) { this.assignmentFailures = assignmentFailures; this.location = HostAndPort.fromString(location); this.assignmentsPerTablet = assignmentsPerTablet; } private void handleFailures(Collection failures, String message) { for (KeyExtent ke : failures) { List mapFiles = assignmentsPerTablet.get(ke); synchronized (assignmentFailures) { for (PathSize pathSize : mapFiles) { List existingFailures = assignmentFailures.get(pathSize.path); if (existingFailures == null) { existingFailures = new ArrayList<>(); assignmentFailures.put(pathSize.path, existingFailures); } existingFailures.add(ke); } } log.info("Could not assign {} map files to tablet {} because : {}. Will retry ...", mapFiles.size(), ke, message); } } @Override public void run() { HashSet uniqMapFiles = new HashSet<>(); for (List mapFiles : assignmentsPerTablet.values()) for (PathSize ps : mapFiles) uniqMapFiles.add(ps.path); log.debug("Assigning {} map files to {} tablets at {}", uniqMapFiles.size(), assignmentsPerTablet.size(), location); try { List failures = assignMapFiles(context, location, assignmentsPerTablet); handleFailures(failures, "Not Serving Tablet"); } catch (AccumuloException | AccumuloSecurityException e) { handleFailures(assignmentsPerTablet.keySet(), e.getMessage()); } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1984 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/client/BulkImporter.java/#L449-L499 | 2 | 159 | 1984 | minor |
| 2541 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14775 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2541 | 14775 | minor |
| 710 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6764 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 1 | 710 | 6764 | minor |
| 773 | { "answer": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 7288 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 773 | 7288 | minor |
| 1696 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FunctionTagsTable extends Composite { private final FunctionEditorInput functionEditorInput; private final KeyValueSetEditingComposite tagsEditingComposite; private final KeyValueSetDataModel tagsDataModel; public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) { super(parent, SWT.NONE); this.functionEditorInput = functionEditorInput; this.setLayout(new GridLayout()); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList()); tagsEditingComposite = new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH))) .addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH))) .addKeyValidator(new LambdaTagNameValidator()) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSaveTags(); } }) .build(this, tagsDataModel); Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttonComposite.setLayout(new GridLayout(1, false)); refresh(); } public void refresh() { Map tagMap = functionEditorInput.getLambdaClient() .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); tagsDataModel.getPairSet().clear(); for (Entry entry : tagMap.entrySet()) { tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue())); } tagsEditingComposite.refresh(); } private void onSaveTags() { try { AWSLambda lambda = functionEditorInput.getLambdaClient(); Map oldTagMap = lambda .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); List tagKeysToBeRemoved = new ArrayList<>(); for (String key : oldTagMap.keySet()) { if (!tagsDataModel.getPairSet().contains(key)) { tagKeysToBeRemoved.add(key); } } Map tagMap = new HashMap<>(); for (Pair pair : tagsDataModel.getPairSet()) { tagMap.put(pair.getKey(), pair.getValue()); } if (!tagKeysToBeRemoved.isEmpty()) { lambda.untagResource(new UntagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTagKeys(tagKeysToBeRemoved)); } lambda.tagResource(new TagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTags(tagMap)); } catch (AWSLambdaException e) { LambdaPlugin.getDefault().reportException(e.getMessage(), e); } } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 11720 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.java/#L47-L123 | 1 | 1696 | 11720 | minor |
| 633 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6294 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 633 | 6294 | minor |
| 2644 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15149 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2644 | 15149 | major |
| 1610 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11459 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 2 | 1610 | 11459 | minor |
| 824 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ArrayMap extends AbstractMap { private Object[] table; private int size; protected transient Collection values; public ArrayMap() { this(32); } public ArrayMap(int capacity) { table = new Object[capacity * 2]; size = 0; } @Override @SuppressWarnings("unchecked") public V get(Object key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } return null; } @Override @SuppressWarnings("unchecked") public V put(K key, V value) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { V old = (V) table[i + 1]; table[i + 1] = value; return old; } } if (size * 2 == table.length) { Object[] n = new Object[table.length * 2]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = value; return null; } @SuppressWarnings("unchecked") public V getOrCompute(K key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } V v = compute(key); if (size << 1 == table.length) { Object[] n = new Object[table.length << 1]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = v; return v; } protected V compute(K key) { throw new UnsupportedOperationException(); } @Override public Collection values() { if (values == null) { values = new AbstractCollection() { @Override public Iterator iterator() { return new Iterator() { int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public V next() { if (index >= size) { throw new NoSuchElementException(); } return (V) table[(index++ << 1) + 1]; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } return values; } @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { FastEntry entry = new FastEntry(); int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public FastEntry next() { if (index >= size) { throw new NoSuchElementException(); } int i = index << 1; entry.key = (K) table[i]; entry.value = (V) table[i + 1]; index++; return entry; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } static class FastEntry implements Entry { K key; V value; public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 7711 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/resolver/src/main/java/org/apache/felix/resolver/util/ArrayMap.java/#L23-L184 | 2 | 824 | 7711 | minor |
| 424 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4255 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 2 | 424 | 4255 | major |
| 2590 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14997 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2590 | 14997 | critical |
| 4092 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 10781 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 4092 | 10781 | major | ||
| 3876 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10126 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 3876 | 10126 | major |
| 1903 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
blob | data class | t | t | f | data class | blob | 0 | 12365 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 1903 | 12365 | major |
| 2452 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | long method | t | t | f | long method | data class | 0 | 14514 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 1 | 2452 | 14514 | minor |
| 2148 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Not specified | f | f | f | false | 0 | 13280 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 2148 | 13280 | minor | |
| 1620 | YES I found bad smells.The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 11479 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 2 | 1620 | 11479 | major |
| 1867 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12239 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 1867 | 12239 | minor |
| 1609 | YES I found bad smells 1. Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code. 2. Primitive Obsession - the field instrClassId is an integer instead of a dedicated class. 3. Long Parameter List - the constructor has two parameters which could potentially be reduced. 4. Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class. 5. Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes. 6. Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes. 7. Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code2 Primitive Obsession - the field instrClassId is an integer instead of a dedicated class3 Long Parameter List - the constructor has two parameters which could potentially be reduced4 Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class5 Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes6 Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes7 Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods | t | f | f | . Data Clumps - the fields name and classLoaderId seem to be frequently used together in the code.2. Primitive Obsession - the field instrClassId is an integer instead of a dedicated class.3. Long Parameter List - the constructor has two parameters which could potentially be reduced.4. Feature Envy - the methods setInstrClassId() and getInstrClassId() seem to be residing in the wrong class.5. Inappropriate Intimacy - the constructor modifies the external objects classLoaderId and name, suggesting a close relationship between the classes.6. Temporary Field - the field instrClassId is only used temporarily for instrumentation purposes.7. Highly Coupled Classes - the class BaseClassInfo depends heavily on the class loader mechanism and its related fields and methods. | data class | 0 | 11456 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 2 | 1609 | 11456 | major |
| 2617 | YES I found bad smells the bad smells are: 1. Long method 2. Repeating code 3. Feature envy 4. Inconsistent naming conventions 5. Lack of comments 6. Unnecessary comments 7. Tight coupling between classes 8. Violation of single responsibility principle 9. Lack of documentation 10. Unnecessary empty constructors | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | Long method2 Repeating code3 Feature envy4 Inconsistent naming conventions5 Lack of comments6 Unnecessary comments7 Tight coupling between classes8 Violation of single responsibility principle 9 Lack of documentation | t | f | f | . Long method2. Repeating code3. Feature envy4. Inconsistent naming conventions5. Lack of comments6. Unnecessary comments7. Tight coupling between classes8. Violation of single responsibility principle 9. Lack of documentation | data class | 0 | 15049 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 2617 | 15049 | major |
| 83 | { "message": "YES I found bad smells", "bad smells": "1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface CompilationIdentifier { enum Verbosity { /** * Only the unique identifier of the compilation. */ ID, /** * Only the name of the compilation unit. */ NAME, /** * {@link #ID} + a readable description. */ DETAILED } CompilationRequestIdentifier INVALID_COMPILATION_ID = new CompilationRequestIdentifier() { @Override public String toString() { return toString(Verbosity.DETAILED); } @Override public String toString(Verbosity verbosity) { return "InvalidCompilationID"; } @Override public CompilationRequest getRequest() { return null; } }; /** * This method is a shortcut for {@link #toString(Verbosity)} with {@link Verbosity#DETAILED}. */ @Override String toString(); /** * Creates a String representation for this compilation identifier with a given * {@link Verbosity}. */ String toString(Verbosity verbosity); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1197 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.core.common/src/org/graalvm/compiler/core/common/CompilationIdentifier.java/#L33-L80 | 2 | 83 | 1197 | major |
| 2222 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13559 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 2222 | 13559 | minor |
| 2549 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14794 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 2 | 2549 | 14794 | minor |
| 438 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 4293 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 438 | 4293 | critical |
| 881 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainFragment extends Fragment implements Updatable { /** * The {@link SwipeRefreshLayout.OnRefreshListener} is also an {@link Observable}. It is * observed by the {@link UsernamesRepository}, an update is triggered whenever * {@link SwipeRefreshLayout.OnRefreshListener#onRefresh()} is fired. */ private OnRefreshObservable refreshObservable; /** * The {@link UsernamesRepository} takes care of providing the data to this fragment. It is an * {@link Updatable} because changes in the {@link OnRefreshObservable} require that it updates * its list of usernames. It is also an {@link Observable} and is observed by this MainFragment. */ private UsernamesRepository usernamesRepository; private ListAdapter listAdapter; private ListView listView; private SwipeRefreshLayout swipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.main_frag, container, false); listView = (ListView) root.findViewById(R.id.list); // Set pull to refresh as an observable and attach it to the view refreshObservable = new OnRefreshObservable(); swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.refresh_layout); swipeRefreshLayout.setColorSchemeColors( ContextCompat.getColor(getActivity(), R.color.colorPrimary), ContextCompat.getColor(getActivity(), R.color.colorAccent), ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark)); swipeRefreshLayout.setOnRefreshListener(refreshObservable); // Initialise the repository usernamesRepository = new UsernamesRepository(new UsernamesFetcher()); return root; } @Override public void onResume() { super.onResume(); // We make sure the repository observes the refresh listener refreshObservable.addUpdatable(usernamesRepository); /** * We make sure the main fragment observes the repository. This will also trigger the * repository to update itself, via * {@link UsernamesRepository#firstUpdatableAdded(UpdateDispatcher)}. */ usernamesRepository.addUpdatable(this); /** * We update the UI to show the data is being updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); } }); } @Override public void onPause() { super.onPause(); // We remove the observations to avoid triggering updates when they aren't needed refreshObservable.removeUpdatable(usernamesRepository); usernamesRepository.removeUpdatable(this); } /** * As this MainFragment is observing the {@link UsernamesRepository}, this is triggered * whenever the {@link UsernamesRepository} updates itself. */ @Override public void update() { /** * We update the UI to show the data has been updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as not refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); } }); // Check error status if (usernamesRepository.isError()) { // Show error message, do not update list as we still want to show the last known list of // usernames Toast.makeText(getContext(), getResources().getString(R.string.error), Toast.LENGTH_LONG).show(); } else { // Update the list of usernames listAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, usernamesRepository.get()); listView.setAdapter(listAdapter); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8020 | https://github.com/google/agera/blob/04045ccbf41ac5fc6806724127b33cbe0dda372c/samples/BasicSample/app/src/main/java/com/example/android/agera/basicsample/MainFragment.java/#L42-L150 | 2 | 881 | 8020 | minor |
| 1467 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | f | f | f | blob | 0 | 11038 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 1 | 1467 | 11038 | critical | ||
| 231 | {"message": "YES I found bad smells. The bad smells are: 1.Long method, 2.Feature envy."} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CrunchInputFormat extends InputFormat { @Override public List getSplits(JobContext job) throws IOException, InterruptedException { List splits = Lists.newArrayList(); Configuration base = job.getConfiguration(); Map>> formatNodeMap = CrunchInputs.getFormatNodeMap(job); // First, build a map of InputFormats to Paths for (Map.Entry>> entry : formatNodeMap.entrySet()) { FormatBundle inputBundle = entry.getKey(); Configuration conf = new Configuration(base); inputBundle.configure(conf); Job jobCopy = new Job(conf); InputFormat format = (InputFormat) ReflectionUtils.newInstance(inputBundle.getFormatClass(), jobCopy.getConfiguration()); if (format instanceof FileInputFormat && !conf.getBoolean(RuntimeParameters.DISABLE_COMBINE_FILE, true)) { format = new CrunchCombineFileInputFormat(jobCopy); } for (Map.Entry> nodeEntry : entry.getValue().entrySet()) { Integer nodeIndex = nodeEntry.getKey(); List paths = nodeEntry.getValue(); FileInputFormat.setInputPaths(jobCopy, paths.toArray(new Path[paths.size()])); // Get splits for each input path and tag with InputFormat // and Mapper types by wrapping in a TaggedInputSplit. List pathSplits = format.getSplits(jobCopy); for (InputSplit pathSplit : pathSplits) { splits.add(new CrunchInputSplit(pathSplit, inputBundle, nodeIndex, jobCopy.getConfiguration())); } } } return splits; } @Override public RecordReader createRecordReader(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { return new CrunchRecordReader(inputSplit, context); } } |
blob | 1.long method, 2.feature envy. | t | t | f | 1.long method, 2.feature envy. | blob | 0 | 2520 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-core/src/main/java/org/apache/crunch/impl/mr/run/CrunchInputFormat.java/#L39-L79 | 2 | 231 | 2520 | minor |
| 44 | { "message": "YES, I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Bundle[] getFragments(Bundle bundle) { if (packageAdmin == null) throw new IllegalStateException("Not started"); //$NON-NLS-1$ return packageAdmin.getFragments(bundle); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 830 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.equinox.jsp.jasper/src/org/eclipse/equinox/internal/jsp/jasper/Activator.java/#L71-L76 | 1 | 44 | 830 | minor |
| 494 | YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy (methods return values from private methods only in order pass them to other methods) 4. Lack of readability and understandability due to unclear method names and lack of comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Duplicated code2 Long method3 Feature envy (methods return values from private methods only in order pass them to other methods)4 Lack of readability and understandability due to unclear method names and lack of comments | t | f | f | . Duplicated code2. Long method3. Feature envy (methods return values from private methods only in order pass them to other methods)4. Lack of readability and understandability due to unclear method names and lack of comments. | data class | 0 | 4985 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 494 | 4985 | minor |
| 1137 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Repeated code in getters and setters"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | long method, repeated code in getters and setters | t | t | f | long method, repeated code in getters and setters | data class | 0 | 10065 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 2 | 1137 | 10065 | minor |
| 685 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UnknownActivationContextCheck(false) @WhitelistAccessOnly @ContentType("text/html") @Import(stylesheet = "dashboard.css") public class T5Dashboard extends AbstractInternalPage { @Inject @Symbol(SymbolConstants.TAPESTRY_VERSION) @Property private String frameworkVersion; @Property @Inject @Symbol(SymbolConstants.PRODUCTION_MODE) private boolean productionMode; @Inject @Property private DashboardManager dashboardManager; @Property private String tabName; private String activeTab; public String getTabClass() { return tabName.equalsIgnoreCase(activeTab) ? "active" : null; } public Block getContent() { return dashboardManager.getTabContent(activeTab); } void onActivate() { activeTab = dashboardManager.getTabNames().get(0); } boolean onActivate(String tabName) { activeTab = tabName; return true; } String onPassivate() { return activeTab; } } |
data class | 1. blob, 2. long method | t | t | f | 1. blob, 2. long method | data class | 0 | 6616 | https://github.com/apache/tapestry-5/blob/542950fc0266e8f9be1aacb5d6ba92146ae20f1b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/pages/T5Dashboard.java/#L27-L78 | 1 | 685 | 6616 | minor |
| 1221 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Inappropriate naming, 4. Long parameter list, 5. Indecent exposure/Inappropriate intimacy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method, 2 Feature envy, 3 Inappropriate naming, 4 Long parameter list, 5 Indecent exposure/Inappropriate intimacy | t | f | f | . Long method, 2. Feature envy, 3. Inappropriate naming, 4. Long parameter list, 5. Indecent exposure/Inappropriate intimacy. | data class | 0 | 10334 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 1221 | 10334 | major |
| 3429 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class DFA28 extends DFA { public DFA28(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 28; this.eot = dfa_9; this.eof = dfa_21; this.min = dfa_10; this.max = dfa_11; this.accept = dfa_12; this.special = dfa_13; this.transition = dfa_14; } public String getDescription() { return "4005:2: ( rule__Object__UnorderedGroup_5__5 )?"; } public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_0 = input.LA(1); int index28_0 = input.index(); input.rewind(); s = -1; if ( LA28_0 == 19 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 0) ) {s = 1;} else if ( LA28_0 == 20 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 1) ) {s = 2;} else if ( LA28_0 == 21 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 2) ) {s = 3;} else if ( LA28_0 == 33 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 3) ) {s = 4;} else if ( LA28_0 == 26 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 5;} else if ( LA28_0 == 27 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 6;} else if ( LA28_0 == 22 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 5) ) {s = 7;} else if ( LA28_0 == 24 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 6) ) {s = 8;} else if ( LA28_0 == 25 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 7) ) {s = 9;} else if ( (LA28_0==EOF||LA28_0==17) ) {s = 10;} input.seek(index28_0); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6797 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/ide/contentassist/antlr/internal/InternalBug304681TestLanguageParser.java/#L20062-L20120 | 2 | 3429 | 6797 | minor |
| 566 | YES I found bad smells. The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class ProxiedNiFiClient implements NiFiClient { private final String proxiedEntity; private final NiFiClient wrappedClient; public ProxiedNiFiClient(final NiFiClient wrappedClient, final String proxiedEntity) { this.proxiedEntity = proxiedEntity; this.wrappedClient = wrappedClient; } @Override public ControllerClient getControllerClient() { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForToken(String token) { return wrappedClient.getControllerClientForToken(token); } @Override public FlowClient getFlowClient() { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForToken(String token) { return wrappedClient.getFlowClientForToken(token); } @Override public ProcessGroupClient getProcessGroupClient() { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForToken(String token) { return wrappedClient.getProcessGroupClientForToken(token); } @Override public VersionsClient getVersionsClient() { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForToken(String token) { return wrappedClient.getVersionsClientForToken(token); } @Override public void close() throws IOException { wrappedClient.close(); } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 5719 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiClientFactory.java/#L113-L187 | 2 | 566 | 5719 | critical |
| 131 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Anonymous inner class" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static long gzip(final ByteSource in, final ByteSink out, Predicate shouldRetry) { return StreamUtils.retryCopy( in, new ByteSink() { @Override public OutputStream openStream() throws IOException { return new GZIPOutputStream(out.openStream()); } }, shouldRetry, DEFAULT_RETRY_COUNT ); } |
feature envy | long method, anonymous inner class | t | t | f | long method, anonymous inner class | feature envy | 0 | 1618 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/utils/CompressionUtils.java/#L491-L506 | 2 | 131 | 1618 | minor |
| 2505 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 14667 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2505 | 14667 | critical |
| 2133 | SequenceFileReader YES, I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Conditional complexity 4. Feature envy 5. Inconsistent formatting 6. Confusing variable names 7. Lack of encapsulation 8. Empty catch block 9. Incomplete error handling 10. Inconsistent commenting 11. Long parameter list 12. Cluttered and unorganized code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | Long method2 Duplicate code3 Conditional complexity4 Feature envy5 Inconsistent formatting6 Confusing variable names7 Lack of encapsulation8 Empty catch block9 Incomplete error handling | t | f | f | . Long method2. Duplicate code3. Conditional complexity4. Feature envy5. Inconsistent formatting6. Confusing variable names7. Lack of encapsulation8. Empty catch block9. Incomplete error handling | data class | 0 | 13238 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 2 | 2133 | 13238 | major |
| 2150 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13287 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 2150 | 13287 | minor |
| 1191 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 10256 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 1 | 1191 | 10256 | minor |
| 211 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 2314 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 1 | 211 | 2314 | major |
| 2338 | {"response": "YES I found bad smells", "detectedBadSmells": [{"1": "Long Method"}, {"2": "Data Class"}]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | 1: long method, 2: data class | t | t | f | 1: long method, 2: data class | blob | 0 | 14167 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 1 | 2338 | 14167 | minor |
| 3429 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class DFA28 extends DFA { public DFA28(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 28; this.eot = dfa_9; this.eof = dfa_21; this.min = dfa_10; this.max = dfa_11; this.accept = dfa_12; this.special = dfa_13; this.transition = dfa_14; } public String getDescription() { return "4005:2: ( rule__Object__UnorderedGroup_5__5 )?"; } public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_0 = input.LA(1); int index28_0 = input.index(); input.rewind(); s = -1; if ( LA28_0 == 19 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 0) ) {s = 1;} else if ( LA28_0 == 20 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 1) ) {s = 2;} else if ( LA28_0 == 21 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 2) ) {s = 3;} else if ( LA28_0 == 33 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 3) ) {s = 4;} else if ( LA28_0 == 26 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 5;} else if ( LA28_0 == 27 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 6;} else if ( LA28_0 == 22 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 5) ) {s = 7;} else if ( LA28_0 == 24 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 6) ) {s = 8;} else if ( LA28_0 == 25 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 7) ) {s = 9;} else if ( (LA28_0==EOF||LA28_0==17) ) {s = 10;} input.seek(index28_0); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6797 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/ide/contentassist/antlr/internal/InternalBug304681TestLanguageParser.java/#L20062-L20120 | 1 | 3429 | 6797 | minor |
| 1222 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10338 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 1222 | 10338 | minor |
| 1801 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicated code 3. Feature envy 4. Primitive obsession 5. Incomplete library class 6. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SafeFileOutputStream extends FilterOutputStream { private final Path desiredFile; private Path tempFile; boolean desiredAlreadyExisted; public SafeFileOutputStream(Path file) throws IOException { this(file, tempFile(file)); } public SafeFileOutputStream(Path desiredFile, Path tempFile) throws IOException { super(Files.newOutputStream(tempFile)); this.desiredFile = desiredFile; this.tempFile = tempFile; // Some useful things to check that we preferably don't want to fail on // close() desiredAlreadyExisted = Files.exists(desiredFile); Path desiredFolder = this.desiredFile.getParent(); if (desiredAlreadyExisted) { if (!Files.isWritable(desiredFile)) { throw new FileNotFoundException("Can't write to " + desiredFile); } } else { if (!Files.exists(desiredFolder)) { throw new FileNotFoundException("Folder does not exist: " + desiredFolder); } if (!Files.isDirectory(desiredFolder)) { throw new FileNotFoundException("Not a directory: " + desiredFolder); } } if (!Files.isWritable(desiredFolder)) { throw new FileNotFoundException("Can't modify folder " + desiredFolder); } } private static Path tempFile(Path file) throws IOException { return Files.createTempFile(file.getParent(), file.getFileName() .toString(), ".tmp"); } @Override public void close() throws IOException { // If super.close fails - we leave the tempfiles behind super.close(); if (!Files.exists(tempFile)) { // Probably something went wrong before close called, // like rollback() return; } Path beforeDeletion = null; try { if (desiredAlreadyExisted) { // In case renaming goes wrong, we don't want to have already // deleted the // desired file. So we'll rename it to another temporary file // instead which // we can delete on successful rename. beforeDeletion = tempFile(desiredFile); if (!Files.deleteIfExists(beforeDeletion)) { // Should not happen, we just made it! throw new IOException("Can't delete temporary file " + beforeDeletion); } Files.move(desiredFile, beforeDeletion, StandardCopyOption.ATOMIC_MOVE); } try { Files.move(tempFile, desiredFile, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { // We'll leave our tempFiles for recovery. tempFile = null; beforeDeletion = null; if (Files.exists(desiredFile)) { // Someone else added or replaced the file afterwards, // kind-a OK return; } throw e; } } finally { if (beforeDeletion != null) { Files.deleteIfExists(beforeDeletion); } if (tempFile != null) { Files.deleteIfExists(tempFile); } } } public void rollback() throws IOException { super.close(); Files.deleteIfExists(tempFile); } } |
blob | Long method2 Duplicated code3 Feature envy4 Primitive obsession5 Incomplete library class6 Inappropriate intimacy | t | f | f | . Long method2. Duplicated code3. Feature envy4. Primitive obsession5. Incomplete library class6. Inappropriate intimacy | blob | 0 | 12018 | https://github.com/apache/incubator-taverna-engine/blob/98536c6b702a0541debbb66be996455384561b54/taverna-prov/src/main/java/org/apache/taverna/prov/SafeFileOutputStream.java/#L36-L137 | 2 | 1801 | 12018 | minor |
| 967 | YES I found bad smells the bad smells are: 1. Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc. are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods. 2. Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc., which may cause confusion and difficulty in understanding its structure and functionality. 3. Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods2 Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc, which may cause confusion and difficulty in understanding its structure and functionality3 Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy | t | f | f | . Feature envy: The methods getExtensions(), setExtensions(), getId(), setId(), etc. are mostly accessing and manipulating the properties of the EObject class, indicating that they would be better placed within the class itself rather than as external methods.2. Message chains: The EObject class contains multiple attributes with nested namespaces, such as extensions, id, type, version, etc., which may cause confusion and difficulty in understanding its structure and functionality.3. Duplicated code: The methods getExtensions() and getVersion() have duplicated logic within their methods, indicating a potential need for refactoring to remove this redundancy. | data class | 0 | 8646 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 967 | 8646 | major |
| 694 | YES, I found bad smells the bad smells are: 1. Long method 2. Repeated code 3. Primitive obsession 4. Feature envy 5. Temporary fields 6. Inappropriate intimacy 7. Lack of encapsulation 8. Incomplete encapsulation 9. Low cohesion 10. Magic numbers/literals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
blob | Long method2 Repeated code3 Primitive obsession4 Feature envy5 Temporary fields 6 Inappropriate intimacy7 Lack of encapsulation 8 Incomplete encapsulation 9 Low cohesion | t | f | f | . Long method2. Repeated code3. Primitive obsession4. Feature envy5. Temporary fields 6. Inappropriate intimacy7. Lack of encapsulation 8. Incomplete encapsulation 9. Low cohesion | blob | 0 | 6656 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 2 | 694 | 6656 | minor |
| 751 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JavaTimeSupplementary_es_AR extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final String[] sharedAmPmMarkers = { "a.m.", "p.m.", }; final String[] sharedDatePatterns = { "GGGG y MMMM d, EEEE", "GGGG y MMMM d", "GGGG y MMM d", "dd/MM/yy G", }; final String[] sharedDayNarrows = { "d", "l", "m", "m", "j", "v", "s", }; final String[] sharedTimePatterns = { "HH:mm:ss zzzz", "HH:mm:ss z", "HH:mm:ss", "HH:mm", }; final String[] sharedJavaTimeDatePatterns = { "G y MMMM d, EEEE", "G y MMMM d", "G y MMM d", "dd/MM/yy GGGGG", }; return new Object[][] { { "field.dayperiod", "a.m./p.m." }, { "islamic.AmPmMarkers", sharedAmPmMarkers }, { "islamic.DatePatterns", sharedDatePatterns }, { "islamic.DayNarrows", sharedDayNarrows }, { "islamic.TimePatterns", sharedTimePatterns }, { "islamic.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "islamic.narrow.AmPmMarkers", sharedAmPmMarkers }, { "java.time.buddhist.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.islamic.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.roc.DatePatterns", sharedJavaTimeDatePatterns }, { "roc.AmPmMarkers", sharedAmPmMarkers }, { "roc.DatePatterns", sharedDatePatterns }, { "roc.DayNarrows", sharedDayNarrows }, { "roc.MonthAbbreviations", new String[] { "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sep.", "oct.", "nov.", "dic.", "", } }, { "roc.MonthNarrows", new String[] { "e", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d", "", } }, { "roc.TimePatterns", sharedTimePatterns }, { "roc.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "roc.narrow.AmPmMarkers", sharedAmPmMarkers }, }; } } |
data class | Long method2 Feature envy3 Duplicate code | t | f | f | . Long method2. Feature envy3. Duplicate code | data class | 0 | 7030 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.localedata/share/classes/sun/text/resources/ext/JavaTimeSupplementary_es_AR.java/#L72-L180 | 2 | 751 | 7030 | minor |
| 1281 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } } |
blob | 1. data class, 2. long method | t | t | f | 1. data class, 2. long method | blob | 0 | 10595 | https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 | 1 | 1281 | 10595 | minor |
| 3714 | YES, I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExistingEnumElements extends AbstractEnumRuleElementFinder { private final EnumRule rule = (EnumRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.enumrules.EnumRulesTestLanguage.ExistingEnum"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final EnumLiteralDeclaration cSameNameEnumLiteralDeclaration_0 = (EnumLiteralDeclaration)cAlternatives.eContents().get(0); private final Keyword cSameNameSameNameKeyword_0_0 = (Keyword)cSameNameEnumLiteralDeclaration_0.eContents().get(0); private final EnumLiteralDeclaration cOverriddenLiteralEnumLiteralDeclaration_1 = (EnumLiteralDeclaration)cAlternatives.eContents().get(1); private final Keyword cOverriddenLiteralOverriddenKeyword_1_0 = (Keyword)cOverriddenLiteralEnumLiteralDeclaration_1.eContents().get(0); private final EnumLiteralDeclaration cDifferentNameEnumLiteralDeclaration_2 = (EnumLiteralDeclaration)cAlternatives.eContents().get(2); private final Keyword cDifferentNameDifferentLiteralKeyword_2_0 = (Keyword)cDifferentNameEnumLiteralDeclaration_2.eContents().get(0); //enum ExistingEnum: // SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral"; public EnumRule getRule() { return rule; } //SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral" public Alternatives getAlternatives() { return cAlternatives; } //SameName public EnumLiteralDeclaration getSameNameEnumLiteralDeclaration_0() { return cSameNameEnumLiteralDeclaration_0; } //"SameName" public Keyword getSameNameSameNameKeyword_0_0() { return cSameNameSameNameKeyword_0_0; } //OverriddenLiteral="overridden" public EnumLiteralDeclaration getOverriddenLiteralEnumLiteralDeclaration_1() { return cOverriddenLiteralEnumLiteralDeclaration_1; } //"overridden" public Keyword getOverriddenLiteralOverriddenKeyword_1_0() { return cOverriddenLiteralOverriddenKeyword_1_0; } //DifferentName="DifferentLiteral" public EnumLiteralDeclaration getDifferentNameEnumLiteralDeclaration_2() { return cDifferentNameEnumLiteralDeclaration_2; } //"DifferentLiteral" public Keyword getDifferentNameDifferentLiteralKeyword_2_0() { return cDifferentNameDifferentLiteralKeyword_2_0; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 8980 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.extras.tests/src-gen/org/eclipse/xtext/enumrules/services/EnumRulesTestLanguageGrammarAccess.java/#L88-L122 | 2 | 3714 | 8980 | major |
| 2646 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15154 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 2 | 2646 | 15154 | minor |
| 1631 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11508 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 | 1 | 1631 | 11508 | minor |
| 2442 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc.) 3. Feature envy 4. Inconsistent formatting 5. Useless comments 6. Complicated conditionals 7. Too many responsibilities 8. Duplicate code 9. Tight coupling 10. Dependency issues 11. Inefficient object creation 12. Violation of Single Responsibility Principle 13. Lack of modularity 14. Poor variable naming 15. Lack of encapsulation 16. Lack of abstraction 17. Unnecessary code 18. Use of magic numbers 19. Poor exception handling 20. Unnecessary use of interfaces 21. Violation of Law of Demeter (accessing private fields in other classes) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | Long method 2 Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc) 3 Feature envy 4 Inconsistent formatting 5 Useless comments 6 Complicated conditionals 7 Too many responsibilities 8 Duplicate code 9 Tight coupling | t | f | f | . Long method 2. Inappropriate naming ("DelegatingLayout", "getTargetDecoration", etc.) 3. Feature envy 4. Inconsistent formatting 5. Useless comments 6. Complicated conditionals 7. Too many responsibilities 8. Duplicate code 9. Tight coupling | data class | 0 | 14482 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 2442 | 14482 | minor |
| 864 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | long method | t | t | f | long method | data class | 0 | 7920 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 1 | 864 | 7920 | minor |
| 2553 | { "input_code": "public class Student {\n private String name;\n private int age;\n\n public Student(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void displayInfo() {\n System.out.println(name + \" is \" + age + \" years old.\");\n }\n}", "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | yes i found bad smellsthe bad smells are: 1. long method | t | t | f | yes i found bad smellsthe bad smells are: 1. long method | blob | 0 | 14816 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 1 | 2553 | 14816 | minor |
| 1833 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Code comments that are not helpful or outdated 5. Poor exception handling 6. Inconsistent use of logging levels and messages 7. Poorly named variables and methods 8. Use of legacy code (Deprecated method calls) 9. Unused parameters and unused imports 10. Not following proper coding conventions (e.g. indentation, spacing) 11. Inappropriate use of concurrency (e.g. use of Semaphore instead of ExecutorService) 12. Poor modularity and lack of separation of concerns 13. Lack of error handling and fault tolerance measures 14. Inefficient and repetitive looping constructs 15. Poor use of comments to explain complex logic 16. Violation of Single Responsibility Principle (SRP) 17. Code duplication and violation of DRY (Don't Repeat Yourself) principle 18. Lack of input validation and error checking. 19. Unnecessary use of global variables and fields 20. Poorly organized and structured code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
blob | Long method2 Feature envy3 Duplicate code4 Code comments that are not helpful or outdated5 Poor exception handling6 Inconsistent use of logging levels and messages7 Poorly named variables and methods8 Use of legacy code (Deprecated method calls)9 Unused parameters and unused imports | t | f | f | . Long method2. Feature envy3. Duplicate code4. Code comments that are not helpful or outdated5. Poor exception handling6. Inconsistent use of logging levels and messages7. Poorly named variables and methods8. Use of legacy code (Deprecated method calls)9. Unused parameters and unused imports | blob | 0 | 12129 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 2 | 1833 | 12129 | major |
| 1678 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | t | f | f | feature envy | 0 | 11649 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 1678 | 11649 | major | ||
| 545 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5547 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 545 | 5547 | minor |
| 182 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2086 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/THBaseService.java/#L12256-L12314 | 1 | 182 | 2086 | major | ||
| 1708 | YES I found bad smells the bad smells are: 1.Long method 2.Magic numbers 3.Nested if statements 4.Inconsistent indentation 5.Non-descriptive method name 6. Use of StringBuffer instead of StringBuilder | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GlobbingPathHelper { /** * Converts the provided path containing glob characters * * and ** into a regular expression. The definition matches * that of the GlobbingPathFilter with the addition that this conversion * also supports sub-paths which do not start with a /. * * The rules are: * * leading ** matches /foo and bar * leading /** matches /foo but not bar * intermittent ** matches zero or any number of path elements * trailing ** matches anything not ending with a / * single * matches anything except / * ? is not a special character * anything not a star is wrapped into \Q...\E pairs * * @param pathWithGlobs path that can contain * and ** * @return a regular expression * @see GlobbingPathFilter */ public static String globPathAsRegex(String pathWithGlobs) { if (pathWithGlobs == null) { return null; } else if (!pathWithGlobs.contains("*")) { return pathWithGlobs; } List elements = Lists.newLinkedList(elements(pathWithGlobs)); StringBuffer sb = new StringBuffer(); sb.append("\\Q"); if (pathWithGlobs.startsWith("/")) { sb.append("/"); } if (elements.get(0).equals("**")) { sb.append("\\E[^/]*(/[^/]*)*\\Q"); elements.remove(0); } int size = elements.size(); boolean endsWithStarStar = size == 0 ? false : elements.get(size - 1).equals("**"); if (endsWithStarStar) { elements.remove(size - 1); } boolean addSlash = false; for(int i=0; i<elements.size(); i++) { String pathElem = elements.get(i); if (addSlash) { sb.append("/"); } if (pathElem.equals("**")) { addSlash = false; sb.append("\\E([^/]*/)*\\Q"); } else { sb.append(pathElem.replace("*", "\\E[^/]*\\Q")); addSlash = true; } } if (endsWithStarStar) { sb.append("\\E(/[^/]*)*"); } else if (pathWithGlobs.endsWith("/")) { sb.append("/\\E"); } else { sb.append("\\E"); } return sb.toString(); } } |
blob | Long method 2Magic numbers 3Nested if statements 4Inconsistent indentation 5Non-descriptive method name 6 Use of StringBuffer instead of StringBuilder | t | f | f | .Long method 2.Magic numbers 3.Nested if statements 4.Inconsistent indentation 5.Non-descriptive method name 6. Use of StringBuffer instead of StringBuilder | blob | 0 | 11756 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/observation/filter/GlobbingPathHelper.java/#L27-L94 | 2 | 1708 | 11756 | minor |
| 1087 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9710 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 2 | 1087 | 9710 | minor |
| 532 | YES, I found bad smells the bad smells are: 1.Long method, 2.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | Long method,2Feature envy: | t | f | f | .Long method, 2.Feature envy: | blob | 0 | 5478 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 2 | 532 | 5478 | minor |
| 182 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2086 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/THBaseService.java/#L12256-L12314 | 2 | 182 | 2086 | major | ||
| 1119 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9960 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1119 | 9960 | major |
| 2415 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14419 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 2415 | 14419 | minor |
| 1612 | YES I found bad smells. The bad smells are: 1. Lack of comments/documentation. 2. Class name does not accurately describe its purpose/function. 3. Method names do not accurately describe their purpose/function. 4. Getter and setter methods are not necessary for this class. 5. Variables are not declared as private. 6. Constructor is not necessary for this class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Lack of comments/documentation2 Class name does not accurately describe its purpose/function3 Method names do not accurately describe their purpose/function4 Getter and setter methods are not necessary for this class5 Variables are not declared as private6 Constructor is not necessary for this class | t | f | f | . Lack of comments/documentation.2. Class name does not accurately describe its purpose/function.3. Method names do not accurately describe their purpose/function.4. Getter and setter methods are not necessary for this class.5. Variables are not declared as private.6. Constructor is not necessary for this class. | data class | 0 | 11467 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 1612 | 11467 | minor |
| 2489 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Magic numbers 4. Deeply nested code 5. Feature envy 6. Inconsistent naming convention 7. Use of static variables and methods 8. Lack of proper comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | Long method2 Long parameter list3 Magic numbers4 Deeply nested code5 Feature envy6 Inconsistent naming convention7 Use of static variables and methods8 Lack of proper comments and documentation | t | f | f | . Long method2. Long parameter list3. Magic numbers4. Deeply nested code5. Feature envy6. Inconsistent naming convention7. Use of static variables and methods8. Lack of proper comments and documentation. | data class | 0 | 14615 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 2489 | 14615 | minor |
| 40 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 769 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 1 | 40 | 769 | minor |
| 1869 | {"output":{"message":"YES I found bad smells","bad smells":["Blob","Long Method","Data Class"]}} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | {"message" | t | f | f | {"message" | data class | 0 | 12245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 1869 | 12245 | major |
| 691 | {"output": "YES, I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6652 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 1 | 691 | 6652 | major |
| 1489 | YES I found bad smells the bad smells are: 1. Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks. 2. Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks2 Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly | t | f | f | . Long method: The class has a long method called "reset" which has many lines of code and performs multiple tasks.2. Feature envy: The class has multiple methods that access and modify the state of the class fields, indicating that they may not be encapsulated properly. | data class | 0 | 11106 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 2 | 1489 | 11106 | major |
| 332 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract static class Builder> { protected abstract T self(); protected Long id; protected String name; protected String description; /** * @see Option#getId() */ public T id(Long id) { this.id = id; return self(); } /** * @see Option#getName() */ public T name(String name) { this.name = name; return self(); } /** * @see Option#getDescription() */ public T description(String description) { this.description = description; return self(); } public Option build() { return new Option(id, name, description); } public T fromOption(Option in) { return this .id(in.getId()) .name(in.getName()) .description(in.getDescription()); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 3402 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Option.java/#L48-L89 | 2 | 332 | 3402 | major |
| 753 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EventAdapterGenerator { public static AdapterClassLoader ldr = new AdapterClassLoader(); static Class EVENTLISTENER = null; static String CLASSPACKAGE = "org/apache/bsf/util/event/adapters/"; static String WRITEDIRECTORY = null; // starting 8 bytes of all Java Class files static byte CLASSHEADER[]; // constant pool items found in all event adapters static short BASECPCOUNT; // number of cp items + 1 ( cp item # 0 reserved for JVM ) static byte BASECP[]; // // some bytes in the middle of the class file (see below) static byte FIXEDCLASSBYTES[]; // the initialization method, noargs constructor static byte INITMETHOD[]; private static BSF_Log logger=null; /* The static initializer */ static { // logger = LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); logger = BSF_LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); String USERCLASSPACKAGE = System.getProperty("DynamicEventClassPackage", ""); if (!USERCLASSPACKAGE.equals("")) { CLASSPACKAGE = USERCLASSPACKAGE; } if(CLASSPACKAGE.length() > 0 ) { CLASSPACKAGE = CLASSPACKAGE.replace('\\','/'); if(!CLASSPACKAGE.endsWith("/")) { CLASSPACKAGE = CLASSPACKAGE+"/"; } } WRITEDIRECTORY = System.getProperty("DynamicEventClassWriteDirectory",CLASSPACKAGE); if(WRITEDIRECTORY.length() > 0 ) { WRITEDIRECTORY = WRITEDIRECTORY.replace('\\','/'); if(!WRITEDIRECTORY.endsWith("/")) { WRITEDIRECTORY = WRITEDIRECTORY+"/"; } } try // { EVENTLISTENER = Class.forName("java.util.EventListener"); } { // EVENTLISTENER = Thread.currentThread().getContextClassLoader().loadClass ("java.util.EventListener"); // rgf, 2006-01-05 // rgf, 20070917: first try context class loader, then BSFManager's defining class loader EVENTLISTENER=null; ClassLoader tccl=Thread.currentThread().getContextClassLoader(); if (tccl!=null) { try { EVENTLISTENER = tccl.loadClass ("java.util.EventListener"); } catch(ClassNotFoundException ex01) {} } if (EVENTLISTENER==null) // did not work, try to load it via the definedClassLoader { EVENTLISTENER = BSFManager.getDefinedClassLoader().loadClass ("java.util.EventListener"); } } catch(ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // start of the Java Class File CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xCA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xFE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)3); // minor version CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)45); // major version // Start the constant pool for base items in all event adapter classes BASECPCOUNT = 17; // number of cp items + 1 ( cp item # 0 reserved for JVM ) // cp item 01 BASECP = Bytecode.addUtf8(BASECP,"()V"); // cp item 02 BASECP = Bytecode.addUtf8(BASECP,""); // cp item 03 BASECP = Bytecode.addUtf8(BASECP,"Code"); // cp item 04 BASECP = Bytecode.addUtf8(BASECP,"eventProcessor"); // cp item 05 BASECP = Bytecode.addUtf8(BASECP,"java/lang/Object"); // cp item 06 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventAdapterImpl"); // cp item 07 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventProcessor"); // cp item 08 BASECP = Bytecode.addUtf8(BASECP,"(Ljava/lang/String;[Ljava/lang/Object;)V"); // cp item 09 BASECP = Bytecode.addUtf8(BASECP,"Lorg/apache/bsf/util/event/EventProcessor;"); // cp item 10 BASECP = Bytecode.addClass(BASECP,(short)5); // Class "java/lang/Object" // cp item 11 BASECP = Bytecode.addClass(BASECP,(short)6); // Class "org/apache/bsf/util/event/EventAdapterImpl" // cp item 12 BASECP = Bytecode.addClass(BASECP,(short)7); // Class "org/apache/bsf/util/event/EventProcessor" // cp item 13 BASECP = Bytecode.addNameAndType(BASECP,(short)2,(short)1); // "" "()V" // cp item 14 BASECP = Bytecode.addNameAndType(BASECP,(short)4,(short)9); // "eventProcessor" "Lorg/apache/bsf/util/event/EventProcessor;" // cp item 15 BASECP = Bytecode.addFieldRef(BASECP,(short)11,(short)14); // cp item 16 BASECP = Bytecode.addMethodRef(BASECP,(short)11,(short)13); // fixed bytes in middle of class file FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0x21); // access_flags (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)20); // this_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)11); // super_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)1); // interface_count (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)19); // interfaces (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0); // field_count (fixed) // initialization method, constructor INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // access_flags INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)2); // name_index "" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // descriptor_index "()V" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // attribute_count INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)3); // attribute_name_index "Code" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)17); // attribute_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_stack INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_locals INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)5); // code_length //code INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0x2A); // aload_0 INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB7); // invokespecial INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)16); // method_ref index INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB1); // return // exception table INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // exception_table_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // attributes_count } /* methods that take an EventListener Class Type to create an EventAdapterClass */ public static Class makeEventAdapterClass(Class listenerType,boolean writeClassFile) { logger.debug("EventAdapterGenerator"); if( EVENTLISTENER.isAssignableFrom(listenerType) ) { boolean exceptionable = false; boolean nonExceptionable = false; byte constantPool[] = null; short cpBaseIndex; short cpCount = 0; short cpExceptionBaseIndex; short exceptionableCount; short nonExceptionableCount; /* Derive Names */ String listenerTypeName = listenerType.getName(); logger.debug("ListenerTypeName: "+listenerTypeName); String adapterClassName = CLASSPACKAGE+ (listenerTypeName.endsWith("Listener") ? listenerTypeName.substring(0, listenerTypeName.length() - 8) : listenerTypeName).replace('.', '_') + "Adapter"; String finalAdapterClassName = adapterClassName; Class cached = null; int suffixIndex = 0; do { if (null != (cached = ldr.getLoadedClass(finalAdapterClassName))) { logger.debug("cached: "+cached); try { if (!listenerType.isAssignableFrom(cached)) finalAdapterClassName = adapterClassName + "_" + suffixIndex++; else return cached; } catch(VerifyError ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); return cached; } } } while (cached != null); String eventListenerName = listenerTypeName.replace('.', '/'); /* method stuff */ java.lang.reflect.Method lms[] = listenerType.getMethods(); /* ****************************************************************************************** */ // Listener interface // Class name cpCount += 4; // cp item 17 constantPool = Bytecode.addUtf8(constantPool,eventListenerName); // cp item 18 constantPool = Bytecode.addUtf8(constantPool,finalAdapterClassName); // cp item 19 constantPool = Bytecode.addClass(constantPool,(short)17); // cp item 20 constantPool = Bytecode.addClass(constantPool,(short)18); // do we have nonExceptionalble event, exceptionable or both for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); if( 0 < exceptionTypes.length) { exceptionable = true; } else { nonExceptionable = true; } }/* End for*/ /* ****************************************************************************************** */ // optional inclusion of nonexceptional events affects exceptional events indices nonExceptionableCount = 0; if(nonExceptionable) { nonExceptionableCount = 3; cpCount += nonExceptionableCount; // cp item 21 constantPool = Bytecode.addUtf8(constantPool,"processEvent"); // cp item 22 constantPool = Bytecode.addNameAndType(constantPool,(short)21,(short)8); // cp item 23 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)22); } /* ****************************************************************************************** */ // optional inclusion of exceptional events affects CP Items which follow for specific methods exceptionableCount = 0; if(exceptionable) { int classIndex = BASECPCOUNT + cpCount + 1; int nameIndex = BASECPCOUNT + cpCount + 0; int natIndex = BASECPCOUNT + cpCount + 3; exceptionableCount = 5; cpCount += exceptionableCount; // cp item 24 or 21 constantPool = Bytecode.addUtf8(constantPool,"processExceptionableEvent"); // cp item 25 or 22 constantPool = Bytecode.addUtf8(constantPool,"java/lang/Exception"); // cp item 26 or 23 constantPool = Bytecode.addClass(constantPool,(short)classIndex); // cp item 27 or 24 constantPool = Bytecode.addNameAndType(constantPool,(short)nameIndex,(short)8); // cp item 28 or 25 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)natIndex); } // base index for method cp references cpBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpBaseIndex: " + cpBaseIndex); for (int i = 0 ; i < lms.length ; ++i) { String eventMethodName = lms[i].getName(); String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); cpCount += 3; // cp items for event methods constantPool = Bytecode.addUtf8(constantPool,eventMethodName); constantPool = Bytecode.addUtf8(constantPool,("(L" + eventName + ";)V")); constantPool = Bytecode.addString(constantPool,(short)(BASECPCOUNT+cpCount-3)); }/* End for*/ boolean propertyChangeFlag[] = new boolean[lms.length]; int cpIndexPCE = 0; for (int i = 0 ; i < lms.length ; ++i) { String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); // cp items for PropertyChangeEvent special handling if(eventName.equalsIgnoreCase("java/beans/PropertyChangeEvent")) { propertyChangeFlag[i] = true; if( 0 == cpIndexPCE ) { constantPool = Bytecode.addUtf8(constantPool,eventName); constantPool = Bytecode.addUtf8(constantPool,"getPropertyName"); constantPool = Bytecode.addUtf8(constantPool,"()Ljava/lang/String;"); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT + cpCount)); constantPool = Bytecode.addNameAndType(constantPool, (short)(BASECPCOUNT + cpCount + 1), (short)(BASECPCOUNT + cpCount + 2)); constantPool = Bytecode.addMethodRef(constantPool, (short)(BASECPCOUNT + cpCount + 3), (short)(BASECPCOUNT + cpCount + 4)); cpCount += 6; cpIndexPCE = BASECPCOUNT + cpCount - 1; } } else { propertyChangeFlag[i] = false; } }/* End for*/ cpExceptionBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpExceptionBaseIndex: " + cpExceptionBaseIndex); int excpIndex[][] = new int[lms.length][]; for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); excpIndex[i] = new int[exceptionTypes.length]; for ( int j = 0 ; j < exceptionTypes.length ; j++) { constantPool = Bytecode.addUtf8(constantPool,exceptionTypes[j].getName().replace('.', '/')); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT+cpCount)); excpIndex[i][j] = BASECPCOUNT + cpCount + 1; cpCount += 2; } }/* End for*/ /* end constant pool */ /* ************************************************************************************************ */ // put the Class byte array together /* start */ byte newClass[] = CLASSHEADER; // magic, version (fixed) short count = (short)(BASECPCOUNT + cpCount); newClass = ByteUtility.addBytes(newClass,count); // constant_pool_count (variable) newClass = ByteUtility.addBytes(newClass,BASECP); // constant_pool (fixed) newClass = ByteUtility.addBytes(newClass,constantPool); // constant_pool (variable) newClass = ByteUtility.addBytes(newClass,FIXEDCLASSBYTES); // see FIXEDCLASSBYTES (fixed) newClass = ByteUtility.addBytes(newClass,(short)(lms.length+1)); // method_count (variable) newClass = ByteUtility.addBytes(newClass,INITMETHOD); // constructor (fixed) // methods /* ****************************************************************************************** */ /* loop over listener methods from listenerType */ for (int i = 0 ; i < lms.length ; ++i) { newClass = ByteUtility.addBytes(newClass,(short)1); // access_flags (fixed) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+0)); // name_index (variable) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+1)); // descriptor_index (variable) newClass = ByteUtility.addBytes(newClass,(short)1); // attribute_count (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // attribute_name_index code(fixed) // Code Attribute Length int length = 32; if( 0 < excpIndex[i].length ) { length += 5 + 8 * ( 1 + excpIndex[i].length ); } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // attribute_length (variable) // start code attribute newClass = ByteUtility.addBytes(newClass,(short)6); // max_stack (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // max_locals (fixed) // Code Length length = 20; if(exceptionable && 0 < excpIndex[i].length) { length += 5; } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // code_length (variable) // start code newClass = ByteUtility.addBytes(newClass,(byte)0x2A); // aload_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB4); // getfield (fixed) newClass = ByteUtility.addBytes(newClass,(short)15); // index (fixed) if(propertyChangeFlag[i]) { // the propertyName is passed as the first parameter newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB6); // invokevirtual (fixed) newClass = ByteUtility.addBytes(newClass,(short)cpIndexPCE); // methodref (variable) } else { // the eventMethodName is passed as the first parameter // Target for method invocation. newClass = ByteUtility.addBytes(newClass,(byte)0x12); // ldc (fixed) newClass = ByteUtility.addBytes(newClass,(byte)(cpBaseIndex+3*i+2)); // index (byte) (variable) } newClass = ByteUtility.addBytes(newClass,(byte)0x04); // iconst_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBD); // anewarray (fixed) newClass = ByteUtility.addBytes(newClass,(short)10); // Class java/lang/Object (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x59); // dup (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x53); // aastore (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB9); // invokeinterface (fixed) // index to processEvent or processExceptionableEvent method length = 23; // actually an index into cp if(exceptionable && nonExceptionable) { // interface method index if( 0 < lms[i].getExceptionTypes().length ) { length += 5; } } else if(exceptionable) { length += 2; } newClass = ByteUtility.addBytes(newClass,(short)length); // index (process??????...) (variable) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x00); // noop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) if(exceptionable && 0 < excpIndex[i].length) { // exception code newClass = ByteUtility.addBytes(newClass,(byte)0x4D); // astore_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2C); // aload_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBF); // athrow (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x57); // pop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) // end code // exception table length = excpIndex[i].length; newClass = ByteUtility.addBytes(newClass,(short)(1+length)); // exception_table_length (variable) for( int j = 0 ; j < length ; j++ ) { // catch exception types and rethrow newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)22); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)20); // handler_pc (fixed) } newClass = ByteUtility.addBytes(newClass,(short)excpIndex[i][j]); // catch_type (variable) } // catch "exception" and trap it newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)25); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)23); // handler_pc (fixed) } if(nonExceptionable) { newClass = ByteUtility.addBytes(newClass,(short)26); } // catch_type (fixed) else // or { newClass = ByteUtility.addBytes(newClass,(short)23); } // catch_type (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)0); } // exception_table_length (fixed) // attributes on the code attribute (none) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) // end code attribute }/* End for*/ // Class Attributes (none for this) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) /* done */ logger.debug("adapterName: " + finalAdapterClassName); logger.debug("cpCount: " + count + " = " + BASECPCOUNT + " + " + cpCount); logger.debug("methodCount: " + (lms.length+1)); // output to disk class file /* ****************************************************************************************** */ // now create the class and load it // return the Class. if (writeClassFile) { try { // removed "WRITEDIRECTORY+", as this path is already part of 'finalAdapterClassName' FileOutputStream fos = new FileOutputStream(finalAdapterClassName+".class"); fos.write(newClass); fos.close(); } catch(IOException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { Class ret = ldr.loadClass(finalAdapterClassName); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } try { Class ret = ldr.defineClass(finalAdapterClassName,newClass); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch(Throwable ex) // rgf, 2012-01-15 { System.err.println(ex.getMessage()); ex.printStackTrace(); } } return null; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 7038 | https://github.com/apache/commons-bsf/blob/88b2601a3caecc32aba38f2b3980d646e9a1b698/src/main/java/org/apache/bsf/util/event/generator/EventAdapterGenerator.java/#L46-L606 | 1 | 753 | 7038 | major |
| 2095 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13145 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 2095 | 13145 | major |
| 1290 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
blob | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | blob | 0 | 10616 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 1290 | 10616 | minor |
| 168 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 | 1 | 168 | 2029 | minor |
| 663 | {"message": "YES I found bad smells", "bad_smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6456 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 663 | 6456 | major |
| 806 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 7625 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 806 | 7625 | major |
| 2446 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 14496 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 1 | 2446 | 14496 | minor |
| 2366 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14296 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 2366 | 14296 | major |
| 158 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 1979 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 158 | 1979 | minor |
| 77 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
blob | Not specified | f | f | f | false | 0 | 1159 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 1 | 77 | 1159 | minor | |
| 327 | YES I found bad smells the bad smells are: 1. Long method 2. No cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method 2 No cohesion | t | f | f | . Long method 2. No cohesion | data class | 0 | 3381 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 327 | 3381 | minor |
| 1457 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.class, org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.Builder.class); } // Construct using org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); guaranteedTaskCount_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto getDefaultInstanceForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance(); } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto build() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto buildPartial() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = new org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.guaranteedTaskCount_ = guaranteedTaskCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) { return mergeFrom((org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto other) { if (other == org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance()) return this; if (other.hasGuaranteedTaskCount()) { setGuaranteedTaskCount(other.getGuaranteedTaskCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 guaranteed_task_count = 1; private int guaranteedTaskCount_ ; /** * optional int32 guaranteed_task_count = 1; */ public boolean hasGuaranteedTaskCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int32 guaranteed_task_count = 1; */ public int getGuaranteedTaskCount() { return guaranteedTaskCount_; } /** * optional int32 guaranteed_task_count = 1; */ public Builder setGuaranteedTaskCount(int value) { bitField0_ |= 0x00000001; guaranteedTaskCount_ = value; onChanged(); return this; } /** * optional int32 guaranteed_task_count = 1; */ public Builder clearGuaranteedTaskCount() { bitField0_ = (bitField0_ & ~0x00000001); guaranteedTaskCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:UpdateQueryRequestProto) } |
blob | long method | t | t | f | long method | blob | 0 | 11016 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/llap-common/src/gen/protobuf/gen-java/org/apache/hadoop/hive/llap/plugin/rpc/LlapPluginProtocolProtos.java/#L286-L435 | 1 | 1457 | 11016 | minor |
| 603 | YES I found bad smells the bad smells are: 1. Long method 2. Code repetition 3. Inconsistent formatting and indentation 4. Lack of comments and documentation 5. Poor variable naming (e.g. "d", "v", "R") 6. Feature envy (class is performing actions that should be done by other classes) 7. Class is responsible for too many tasks (violating Single Responsibility Principle) 8. Lack of error handling and handling of invalid input 9. Use of generic and ambiguous names for methods (e.g. "getKind()") 10. Overuse of annotations (e.g. @DefinedBy(Api.COMPILER_TREE)) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method2 Code repetition3 Inconsistent formatting and indentation4 Lack of comments and documentation5 Poor variable naming (eg "d", "v", "R")6 Feature envy (class is performing actions that should be done by other classes)7 Class is responsible for too many tasks (violating Single Responsibility Principle)8 Lack of error handling and handling of invalid input9 Use of generic and ambiguous names for methods (eg "getKind()") | t | f | f | . Long method2. Code repetition3. Inconsistent formatting and indentation4. Lack of comments and documentation5. Poor variable naming (e.g. "d", "v", "R")6. Feature envy (class is performing actions that should be done by other classes)7. Class is responsible for too many tasks (violating Single Responsibility Principle)8. Lack of error handling and handling of invalid input9. Use of generic and ambiguous names for methods (e.g. "getKind()") | data class | 0 | 6013 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 603 | 6013 | major |
| 1946 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObserveUtil { /* keys used to populate the request context */ public static final String CTX_ENDPOINT = "leshan-endpoint"; public static final String CTX_REGID = "leshan-regId"; public static final String CTX_LWM2M_PATH = "leshan-path"; /** * Create a LWM2M observation from a CoAP request. */ public static Observation createLwM2mObservation(Request request) { String regId = null; String lwm2mPath = null; Map context = null; for (Entry ctx : request.getUserContext().entrySet()) { switch (ctx.getKey()) { case CTX_REGID: regId = ctx.getValue(); break; case CTX_LWM2M_PATH: lwm2mPath = ctx.getValue(); break; case CTX_ENDPOINT: break; default: if (context == null) { context = new HashMap<>(); } context.put(ctx.getKey(), ctx.getValue()); } } ContentFormat contentFormat = null; if (request.getOptions().hasAccept()) { contentFormat = ContentFormat.fromCode(request.getOptions().getAccept()); } return new Observation(request.getToken().getBytes(), regId, new LwM2mPath(lwm2mPath), contentFormat, context); } /** * Create a CoAP observe request context with specific keys needed for internal Leshan working. */ public static Map createCoapObserveRequestContext(String endpoint, String registrationId, ObserveRequest request) { Map context = new HashMap<>(); context.put(CTX_ENDPOINT, endpoint); context.put(CTX_REGID, registrationId); context.put(CTX_LWM2M_PATH, request.getPath().toString()); for (Entry ctx : request.getContext().entrySet()) { context.put(ctx.getKey(), ctx.getValue()); } return context; } public static String extractRegistrationId(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_REGID); } public static String extractLwm2mPath(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_LWM2M_PATH); } public static String extractEndpoint(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_ENDPOINT); } /** * Validate the Californium observation. It is valid if it contains all necessary context for Leshan. */ public static String validateCoapObservation(org.eclipse.californium.core.observe.Observation observation) { if (!observation.getRequest().getUserContext().containsKey(CTX_REGID)) throw new IllegalStateException("missing registrationId info in the request context"); if (!observation.getRequest().getUserContext().containsKey(CTX_LWM2M_PATH)) throw new IllegalStateException("missing lwm2m path info in the request context"); String endpoint = observation.getRequest().getUserContext().get(CTX_ENDPOINT); if (endpoint == null) throw new IllegalStateException("missing endpoint info in the request context"); return endpoint; } } |
blob | data class | t | t | f | data class | blob | 0 | 12519 | https://github.com/eclipse/leshan/blob/eb75fc8b7d5560944e6d532f1a09d5e5c6e54559/leshan-server-cf/src/main/java/org/eclipse/leshan/server/californium/ObserveUtil.java/#L32-L114 | 1 | 1946 | 12519 | minor |
| 1736 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | t | f | f | data class | 0 | 11827 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 1 | 1736 | 11827 | minor | ||
| 104 | {"response":"YES, I found bad smells","bad smells are":["1.Long method","2.Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } } |
blob | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | blob | 0 | 1359 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 | 2 | 104 | 1359 | minor |
| 1012 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void write(DataOutputView out) throws IOException { out.writeInt(position); for (int i = 0; i < position; i++) { out.writeDouble(data[i]); } } |
feature envy | Magic numbers2 Long method | t | f | f | . Magic numbers2. Long method | feature envy | 0 | 9274 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/DoubleValueArray.java/#L179-L186 | 2 | 1012 | 9274 | major |
| 1844 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12159 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 1 | 1844 | 12159 | critical |
| 917 | YES, I found bad smells The detected bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract class RTFParser extends AbstractFilter { /** The current RTF group nesting level. */ public int level; private int state; private StringBuffer currentCharacters; private String pendingKeyword; // where keywords go while we // read their parameters private int pendingCharacter; // for the \'xx construct private long binaryBytesLeft; // in a \bin blob? ByteArrayOutputStream binaryBuf; private boolean[] savedSpecials; /** A stream to which to write warnings and debugging information * while parsing. This is set to System.out to log * any anomalous information to stdout. */ protected PrintStream warnings; // value for the 'state' variable private final int S_text = 0; // reading random text private final int S_backslashed = 1; // read a backslash, waiting for next private final int S_token = 2; // reading a multicharacter token private final int S_parameter = 3; // reading a token's parameter private final int S_aftertick = 4; // after reading \' private final int S_aftertickc = 5; // after reading \'x private final int S_inblob = 6; // in a \bin blob /** Implemented by subclasses to interpret a parameter-less RTF keyword. * The keyword is passed without the leading '/' or any delimiting * whitespace. */ public abstract boolean handleKeyword(String keyword); /** Implemented by subclasses to interpret a keyword with a parameter. * @param keyword The keyword, as with handleKeyword(String). * @param parameter The parameter following the keyword. */ public abstract boolean handleKeyword(String keyword, int parameter); /** Implemented by subclasses to interpret text from the RTF stream. */ public abstract void handleText(String text); public void handleText(char ch) { handleText(String.valueOf(ch)); } /** Implemented by subclasses to handle the contents of the \bin keyword. */ public abstract void handleBinaryBlob(byte[] data); /** Implemented by subclasses to react to an increase * in the nesting level. */ public abstract void begingroup(); /** Implemented by subclasses to react to the end of a group. */ public abstract void endgroup(); // table of non-text characters in rtf static final boolean[] rtfSpecialsTable; static { rtfSpecialsTable = noSpecialsTable.clone(); rtfSpecialsTable['\n'] = true; rtfSpecialsTable['\r'] = true; rtfSpecialsTable['{'] = true; rtfSpecialsTable['}'] = true; rtfSpecialsTable['\\'] = true; } public RTFParser() { currentCharacters = new StringBuffer(); state = S_text; pendingKeyword = null; level = 0; //warnings = System.out; specialsTable = rtfSpecialsTable; } // TODO: Handle wrapup at end of file correctly. public void writeSpecial(int b) throws IOException { write((char)b); } protected void warning(String s) { if (warnings != null) { warnings.println(s); } } public void write(String s) throws IOException { if (state != S_text) { int index = 0; int length = s.length(); while(index < length && state != S_text) { write(s.charAt(index)); index ++; } if(index >= length) return; s = s.substring(index); } if (currentCharacters.length() > 0) currentCharacters.append(s); else handleText(s); } @SuppressWarnings("fallthrough") public void write(char ch) throws IOException { boolean ok; switch (state) { case S_text: if (ch == '\n' || ch == '\r') { break; // unadorned newlines are ignored } else if (ch == '{') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } level ++; begingroup(); } else if(ch == '}') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } if (level == 0) throw new IOException("Too many close-groups in RTF text"); endgroup(); level --; } else if(ch == '\\') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } state = S_backslashed; } else { currentCharacters.append(ch); } break; case S_backslashed: if (ch == '\'') { state = S_aftertick; break; } if (!Character.isLetter(ch)) { char[] newstring = new char[1]; newstring[0] = ch; if (!handleKeyword(new String(newstring))) { warning("Unknown keyword: " + newstring + " (" + (byte)ch + ")"); } state = S_text; pendingKeyword = null; /* currentCharacters is already an empty stringBuffer */ break; } state = S_token; /* FALL THROUGH */ case S_token: if (Character.isLetter(ch)) { currentCharacters.append(ch); } else { pendingKeyword = currentCharacters.toString(); currentCharacters = new StringBuffer(); // Parameter following? if (Character.isDigit(ch) || (ch == '-')) { state = S_parameter; currentCharacters.append(ch); } else { ok = handleKeyword(pendingKeyword); if (!ok) warning("Unknown keyword: " + pendingKeyword); pendingKeyword = null; state = S_text; // Non-space delimiters get included in the text if (!Character.isWhitespace(ch)) write(ch); } } break; case S_parameter: if (Character.isDigit(ch)) { currentCharacters.append(ch); } else { /* TODO: Test correct behavior of \bin keyword */ if (pendingKeyword.equals("bin")) { /* magic layer-breaking kwd */ long parameter = Long.parseLong(currentCharacters.toString()); pendingKeyword = null; state = S_inblob; binaryBytesLeft = parameter; if (binaryBytesLeft > Integer.MAX_VALUE) binaryBuf = new ByteArrayOutputStream(Integer.MAX_VALUE); else binaryBuf = new ByteArrayOutputStream((int)binaryBytesLeft); savedSpecials = specialsTable; specialsTable = allSpecialsTable; break; } int parameter = Integer.parseInt(currentCharacters.toString()); ok = handleKeyword(pendingKeyword, parameter); if (!ok) warning("Unknown keyword: " + pendingKeyword + " (param " + currentCharacters + ")"); pendingKeyword = null; currentCharacters = new StringBuffer(); state = S_text; // Delimiters here are interpreted as text too if (!Character.isWhitespace(ch)) write(ch); } break; case S_aftertick: if (Character.digit(ch, 16) == -1) state = S_text; else { pendingCharacter = Character.digit(ch, 16); state = S_aftertickc; } break; case S_aftertickc: state = S_text; if (Character.digit(ch, 16) != -1) { pendingCharacter = pendingCharacter * 16 + Character.digit(ch, 16); ch = translationTable[pendingCharacter]; if (ch != 0) handleText(ch); } break; case S_inblob: binaryBuf.write(ch); binaryBytesLeft --; if (binaryBytesLeft == 0) { state = S_text; specialsTable = savedSpecials; savedSpecials = null; handleBinaryBlob(binaryBuf.toByteArray()); binaryBuf = null; } } } /** Flushes any buffered but not yet written characters. * Subclasses which override this method should call this * method before flushing * any of their own buffers. */ public void flush() throws IOException { super.flush(); if (state == S_text && currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } } /** Closes the parser. Currently, this simply does a flush(), * followed by some minimal consistency checks. */ public void close() throws IOException { flush(); if (state != S_text || level > 0) { warning("Truncated RTF file."); /* TODO: any sane way to handle termination in a non-S_text state? */ /* probably not */ /* this will cause subclasses to behave more reasonably some of the time */ while (level > 0) { endgroup(); level --; } } super.close(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 8249 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/rtf/RTFParser.java/#L41-L334 | 2 | 917 | 8249 | major |
| 2625 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15077 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 2625 | 15077 | minor |
| 1858 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12217 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 1858 | 12217 | major |
| 265 | { "message": "YES I found bad smells", "bad smells are:": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | long method | t | t | f | long method | blob | 0 | 2876 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 1 | 265 | 2876 | major |
| 2008 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive number of parameters 4. Inconsistent naming conventions 5. Use of raw types 6. Unused imports 7. Lack of documentation/comments 8. Use of regex without clear purpose 9. Unnecessary getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | Long method2 Feature envy3 Excessive number of parameters4 Inconsistent naming conventions5 Use of raw types6 Unused imports7 Lack of documentation/comments8 Use of regex without clear purpose9 Unnecessary getters and setters | t | f | f | . Long method2. Feature envy3. Excessive number of parameters4. Inconsistent naming conventions5. Use of raw types6. Unused imports7. Lack of documentation/comments8. Use of regex without clear purpose9. Unnecessary getters and setters | data class | 0 | 12738 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 2 | 2008 | 12738 | critical |
| 2367 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | f | f | f | data class | 0 | 14300 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 2367 | 14300 | minor | ||
| 1691 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11710 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 | 2 | 1691 | 11710 | minor |
| 1474 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11056 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 1474 | 11056 | minor |
| 1586 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
blob | Data Class | t | f | f | Data Class | blob | 0 | 11369 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 1 | 1586 | 11369 | major |
| 2027 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Switch statement 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | Magic numbers2 Switch statement3 Long method | t | f | f | . Magic numbers2. Switch statement3. Long method | feature envy | 0 | 12805 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 2 | 2027 | 12805 | major |
| 399 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 4069 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 | 2 | 399 | 4069 | critical |
| 2327 | {"response":"YES I found bad smells","bad smells":"1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14144 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 2327 | 14144 | minor |
| 2192 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13474 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 2192 | 13474 | major |
| 1862 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @NbBundle.Messages({ "LocksFeatureUI_show=View by:", "LocksFeatureUI_aggregationByThreads=Threads", "LocksFeatureUI_aggregationByMonitors=Monitors", "LocksFeatureUI_aggregationHint=Results aggregation" }) abstract class LocksFeatureUI extends FeatureUI { private ProfilerToolbar toolbar; private LockContentionPanel locksView; // --- External implementation --------------------------------------------- abstract ProfilerClient getProfilerClient(); abstract void refreshResults(); // --- API implementation -------------------------------------------------- ProfilerToolbar getToolbar() { if (toolbar == null) initUI(); return toolbar; } JPanel getResultsUI() { if (locksView == null) initUI(); return locksView; } void sessionStateChanged(int sessionState) { refreshToolbar(sessionState); if (sessionState == Profiler.PROFILING_INACTIVE || sessionState == Profiler.PROFILING_IN_TRANSITION) { if (locksView != null) locksView.profilingSessionFinished(); } else if (sessionState == Profiler.PROFILING_RUNNING) { if (locksView != null) locksView.profilingSessionStarted(); } } void resetPause() { // if (lrPauseButton != null) lrPauseButton.setSelected(false); } void setForceRefresh() { if (locksView != null) locksView.setForceRefresh(true); } void refreshData() throws ClientUtils.TargetAppOrVMTerminated { if (locksView != null) locksView.refreshData(); } void resetData() { if (locksView != null) locksView.resetData(); } // --- UI ------------------------------------------------------------------ private JLabel shLabel; private ActionPopupButton shAggregation; private void initUI() { assert SwingUtilities.isEventDispatchThread(); // --- Results --------------------------------------------------------- locksView = new LockContentionPanel() { protected ProfilerClient getProfilerClient() { return LocksFeatureUI.this.getProfilerClient(); } }; locksView.lockContentionEnabled(); locksView.putClientProperty("HelpCtx.Key", "ProfileLocks.HelpCtx"); // NOI18N // --- Toolbar --------------------------------------------------------- shLabel = new GrayLabel(Bundle.LocksFeatureUI_show()); Action aThreads = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByThreads()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_THREADS); } }; Action aMonitors = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByMonitors()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_MONITORS); } }; shAggregation = new ActionPopupButton(aThreads, aMonitors); shAggregation.setToolTipText(Bundle.LocksFeatureUI_aggregationHint()); toolbar = ProfilerToolbar.create(true); toolbar.addSpace(2); toolbar.addSeparator(); toolbar.addSpace(5); toolbar.add(shLabel); toolbar.addSpace(2); toolbar.add(shAggregation); // --- Sync UI --------------------------------------------------------- setAggregation(LockContentionPanel.Aggregation.BY_THREADS); sessionStateChanged(getSessionState()); } private void refreshToolbar(final int state) { // if (toolbar != null) SwingUtilities.invokeLater(new Runnable() { // public void run() { // } // }); } private void setAggregation(LockContentionPanel.Aggregation aggregation) { locksView.setAggregation(aggregation); shAggregation.selectAction(aggregation.ordinal()); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12224 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler/src/org/graalvm/visualvm/lib/profiler/v2/features/LocksFeatureUI.java/#L65-L192 | 1 | 1862 | 12224 | minor |
| 2557 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Violating the Single Responsibility Principle 5. Inconsistent naming conventions 6. Lack of proper commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
blob | Long method2 Feature envy3 Duplicate code4 Violating the Single Responsibility Principle5 Inconsistent naming conventions6 Lack of proper commenting/documentation | t | f | f | . Long method2. Feature envy3. Duplicate code4. Violating the Single Responsibility Principle5. Inconsistent naming conventions6. Lack of proper commenting/documentation | blob | 0 | 14832 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 2 | 2557 | 14832 | minor |
| 436 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JpegRewriter extends BinaryFileParser { private static final ByteOrder JPEG_BYTE_ORDER = ByteOrder.BIG_ENDIAN; private static final SegmentFilter EXIF_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isExifSegment(); } }; private static final SegmentFilter XMP_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isXmpSegment(); } }; private static final SegmentFilter PHOTOSHOP_APP13_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isPhotoshopApp13Segment(); } }; /** * Constructor. to guess whether a file contains an image based on its file * extension. */ public JpegRewriter() { setByteOrder(JPEG_BYTE_ORDER); } protected static class JFIFPieces { public final List pieces; public final List segmentPieces; public JFIFPieces(final List pieces, final List segmentPieces) { this.pieces = pieces; this.segmentPieces = segmentPieces; } } protected abstract static class JFIFPiece { protected abstract void write(OutputStream os) throws IOException; @Override public String toString() { return "[" + this.getClass().getName() + "]"; } } protected static class JFIFPieceSegment extends JFIFPiece { public final int marker; private final byte[] markerBytes; private final byte[] segmentLengthBytes; private final byte[] segmentData; public JFIFPieceSegment(final int marker, final byte[] segmentData) { this(marker, ByteConversions.toBytes((short) marker, JPEG_BYTE_ORDER), ByteConversions.toBytes((short) (segmentData.length + 2), JPEG_BYTE_ORDER), segmentData); } JFIFPieceSegment(final int marker, final byte[] markerBytes, final byte[] segmentLengthBytes, final byte[] segmentData) { this.marker = marker; this.markerBytes = markerBytes; this.segmentLengthBytes = segmentLengthBytes; this.segmentData = segmentData; // TODO clone? } @Override public String toString() { return "[" + this.getClass().getName() + " (0x" + Integer.toHexString(marker) + ")]"; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(segmentLengthBytes); os.write(segmentData); } public boolean isApp1Segment() { return marker == JpegConstants.JPEG_APP1_MARKER; } public boolean isAppSegment() { return marker >= JpegConstants.JPEG_APP0_MARKER && marker <= JpegConstants.JPEG_APP15_MARKER; } public boolean isExifSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.EXIF_IDENTIFIER_CODE)) { return false; } return true; } public boolean isPhotoshopApp13Segment() { if (marker != JpegConstants.JPEG_APP13_MARKER) { return false; } if (!new IptcParser().isPhotoshopJpegSegment(segmentData)) { return false; } return true; } public boolean isXmpSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.XMP_IDENTIFIER)) { return false; } return true; } public byte[] getSegmentData() { return segmentData; // TODO clone? } } static class JFIFPieceImageData extends JFIFPiece { private final byte[] markerBytes; private final byte[] imageData; JFIFPieceImageData(final byte[] markerBytes, final byte[] imageData) { super(); this.markerBytes = markerBytes; this.imageData = imageData; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(imageData); } } protected JFIFPieces analyzeJFIF(final ByteSource byteSource) throws ImageReadException, IOException { final List pieces = new ArrayList<>(); final List segmentPieces = new ArrayList<>(); final JpegUtils.Visitor visitor = new JpegUtils.Visitor() { // return false to exit before reading image data. @Override public boolean beginSOS() { return true; } @Override public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) { pieces.add(new JFIFPieceImageData(markerBytes, imageData)); } // return false to exit traversal. @Override public boolean visitSegment(final int marker, final byte[] markerBytes, final int segmentLength, final byte[] segmentLengthBytes, final byte[] segmentData) throws ImageReadException, IOException { final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); pieces.add(piece); segmentPieces.add(piece); return true; } }; new JpegUtils().traverseJFIF(byteSource, visitor); return new JFIFPieces(pieces, segmentPieces); } private interface SegmentFilter { boolean filter(JFIFPieceSegment segment); } protected List removeXmpSegments(final List segments) { return filterSegments(segments, XMP_SEGMENT_FILTER); } protected List removePhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER); } protected List findPhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER, true); } protected List removeExifSegments(final List segments) { return filterSegments(segments, EXIF_SEGMENT_FILTER); } protected List filterSegments(final List segments, final SegmentFilter filter) { return filterSegments(segments, filter, false); } protected List filterSegments(final List segments, final SegmentFilter filter, final boolean reverse) { final List result = new ArrayList<>(); for (final T piece : segments) { if (piece instanceof JFIFPieceSegment) { if (filter.filter((JFIFPieceSegment) piece) ^ !reverse) { result.add(piece); } } else if (!reverse) { result.add(piece); } } return result; } protected List insertBeforeFirstAppSegments( final List segments, final List newSegments) throws ImageWriteException { int firstAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { if (firstAppIndex == -1) { firstAppIndex = i; } } } final List result = new ArrayList(segments); if (firstAppIndex == -1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(firstAppIndex, newSegments); return result; } protected List insertAfterLastAppSegments( final List segments, final List newSegments) throws ImageWriteException { int lastAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { lastAppIndex = i; } } final List result = new ArrayList(segments); if (lastAppIndex == -1) { if (segments.size() < 1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(1, newSegments); } else { result.addAll(lastAppIndex + 1, newSegments); } return result; } protected void writeSegments(final OutputStream outputStream, final List segments) throws IOException { try (DataOutputStream os = new DataOutputStream(outputStream)) { JpegConstants.SOI.writeTo(os); for (final JFIFPiece piece : segments) { piece.write(os); } } } // private void writeSegment(OutputStream os, JFIFPieceSegment piece) // throws ImageWriteException, IOException // { // byte markerBytes[] = convertShortToByteArray(JPEG_APP1_MARKER, // JPEG_BYTE_ORDER); // if (piece.segmentData.length > 0xffff) // throw new JpegSegmentOverflowException("Jpeg segment is too long: " // + piece.segmentData.length); // int segmentLength = piece.segmentData.length + 2; // byte segmentLengthBytes[] = convertShortToByteArray(segmentLength, // JPEG_BYTE_ORDER); // // os.write(markerBytes); // os.write(segmentLengthBytes); // os.write(piece.segmentData); // } public static class JpegSegmentOverflowException extends ImageWriteException { private static final long serialVersionUID = -1062145751550646846L; public JpegSegmentOverflowException(final String message) { super(message); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 4290 | https://github.com/apache/commons-imaging/blob/fa7c16f434061d441d1c0d9dbcfd0f4c3092c880/src/main/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegRewriter.java/#L40-L353 | 2 | 436 | 4290 | major |
| 1433 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
blob | data class | t | t | f | data class | blob | 0 | 10958 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 1 | 1433 | 10958 | minor |
| 3610 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long method" }, { "2": "Feature envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
blob | 1: long method, 2: feature envy | t | t | f | 1: long method, 2: feature envy | blob | 0 | 8057 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 1 | 3610 | 8057 | minor |
| 1954 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 12540 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 1 | 1954 | 12540 | minor |
| 2551 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 14798 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 1 | 2551 | 14798 | minor |
| 5401 | found: "NO, I did not find any bad smell" | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | "NO, I did not find any bad smell" | f | f | f | "NO, I did not find any bad smell" | long method | 0 | 15176 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 5401 | 15176 | minor |
| 641 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 6352 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 2 | 641 | 6352 | critical |
| 4558 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
blob | data class | t | t | f | data class | blob | 0 | 12116 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 1 | 4558 | 12116 | minor |
| 1833 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
blob | t | f | f | blob | 0 | 12129 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 1 | 1833 | 12129 | major | ||
| 1475 | YES I found bad smells The bad smells are: 1. Data clumps 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Data clumps2 Long method 3 Feature envy | t | f | f | . Data clumps2. Long method 3. Feature envy | data class | 0 | 11062 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 1475 | 11062 | major |
| 2210 | { "message": "YES I found bad smells", "detected_bad_smells": { "the_bad_smells_are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | the_bad_smells_are: long method | t | t | f | the_bad_smells_are: long method | blob | 0 | 13520 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 1 | 2210 | 13520 | major |
| 5536 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6190 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5536 | 6190 | minor |
| 989 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9013 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 2 | 989 | 9013 | major |
| 248 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Service public class DepositAccountAssembler { private final PlatformSecurityContext context; private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsHelper savingsHelper; private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final StaffRepositoryWrapper staffRepository; private final FixedDepositProductRepository fixedDepositProductRepository; private final RecurringDepositProductRepository recurringDepositProductRepository; private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final SavingsAccountChargeAssembler savingsAccountChargeAssembler; private final FromJsonHelper fromApiJsonHelper; private final DepositProductAssembler depositProductAssembler; private final PaymentDetailAssembler paymentDetailAssembler; @Autowired public DepositAccountAssembler(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final ClientRepositoryWrapper clientRepository, final GroupRepositoryWrapper groupRepository, final StaffRepositoryWrapper staffRepository, final FixedDepositProductRepository fixedDepositProductRepository, final SavingsAccountRepositoryWrapper savingsAccountRepository, final SavingsAccountChargeAssembler savingsAccountChargeAssembler, final FromJsonHelper fromApiJsonHelper, final DepositProductAssembler depositProductAssembler, final RecurringDepositProductRepository recurringDepositProductRepository, final AccountTransfersReadPlatformService accountTransfersReadPlatformService, final PlatformSecurityContext context, final PaymentDetailAssembler paymentDetailAssembler) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.staffRepository = staffRepository; this.fixedDepositProductRepository = fixedDepositProductRepository; this.savingsAccountRepository = savingsAccountRepository; this.savingsAccountChargeAssembler = savingsAccountChargeAssembler; this.fromApiJsonHelper = fromApiJsonHelper; this.depositProductAssembler = depositProductAssembler; this.recurringDepositProductRepository = recurringDepositProductRepository; this.savingsHelper = new SavingsHelper(accountTransfersReadPlatformService); this.context = context; this.paymentDetailAssembler = paymentDetailAssembler; } /** * Assembles a new {@link SavingsAccount} from JSON details passed in * request inheriting details where relevant from chosen * {@link SavingsProduct}. */ public SavingsAccount assembleFrom(final JsonCommand command, final AppUser submittedBy, final DepositAccountType depositAccountType) { final JsonElement element = command.parsedJson(); final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); SavingsProduct product = null; if (depositAccountType.isFixedDeposit()) { product = this.fixedDepositProductRepository.findOne(productId); if (product == null) { throw new FixedDepositProductNotFoundException(productId); } } else if (depositAccountType.isRecurringDeposit()) { product = this.recurringDepositProductRepository.findOne(productId); if (product == null) { throw new RecurringDepositProductNotFoundException(productId); } } if (product == null) { throw new SavingsProductNotFoundException(productId); } Client client = null; Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; } if (group != null && client != null) { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } accountType = AccountType.JLG; if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); } else { interestRate = product.nominalAnnualInterestRate(); } SavingsCompoundingInterestPeriodType interestCompoundingPeriodType = null; final Integer interestPeriodTypeValue = command.integerValueOfParameterNamed(interestCompoundingPeriodTypeParamName); if (interestPeriodTypeValue != null) { interestCompoundingPeriodType = SavingsCompoundingInterestPeriodType.fromInt(interestPeriodTypeValue); } else { interestCompoundingPeriodType = product.interestCompoundingPeriodType(); } SavingsPostingInterestPeriodType interestPostingPeriodType = null; final Integer interestPostingPeriodTypeValue = command.integerValueOfParameterNamed(interestPostingPeriodTypeParamName); if (interestPostingPeriodTypeValue != null) { interestPostingPeriodType = SavingsPostingInterestPeriodType.fromInt(interestPostingPeriodTypeValue); } else { interestPostingPeriodType = product.interestPostingPeriodType(); } SavingsInterestCalculationType interestCalculationType = null; final Integer interestCalculationTypeValue = command.integerValueOfParameterNamed(interestCalculationTypeParamName); if (interestCalculationTypeValue != null) { interestCalculationType = SavingsInterestCalculationType.fromInt(interestCalculationTypeValue); } else { interestCalculationType = product.interestCalculationType(); } SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = command .integerValueOfParameterNamed(interestCalculationDaysInYearTypeParamName); if (interestCalculationDaysInYearTypeValue != null) { interestCalculationDaysInYearType = SavingsInterestCalculationDaysInYearType.fromInt(interestCalculationDaysInYearTypeValue); } else { interestCalculationDaysInYearType = product.interestCalculationDaysInYearType(); } BigDecimal minRequiredOpeningBalance = null; if (command.parameterExists(minRequiredOpeningBalanceParamName)) { minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); } else { minRequiredOpeningBalance = product.minRequiredOpeningBalance(); } Integer lockinPeriodFrequency = null; if (command.parameterExists(lockinPeriodFrequencyParamName)) { lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); } else { lockinPeriodFrequency = product.lockinPeriodFrequency(); } SavingsPeriodFrequencyType lockinPeriodFrequencyType = null; if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { Integer lockinPeriodFrequencyTypeValue = null; lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); if (lockinPeriodFrequencyTypeValue != null) { lockinPeriodFrequencyType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); } } else { lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); } boolean iswithdrawalFeeApplicableForTransfer = false; if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element, product.currency().getCode()); DepositAccountInterestRateChart accountChart = null; InterestRateChart productChart = null; if (command.parameterExists(chartIdParamName)) { Long chartId = command.longValueOfParameterNamed(chartIdParamName); productChart = product.findChart(chartId); } else { productChart = product.applicableChart(submittedOnDate); } if (productChart != null) { accountChart = DepositAccountInterestRateChart.from(productChart); } boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); if(withHoldTax && product.getTaxGroup() == null){ throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } SavingsAccount account = null; if (depositAccountType.isFixedDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((FixedDepositProduct) product).depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); FixedDepositAccount fdAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(fdAccount); fdAccount.validateDomainRules(); account = fdAccount; } else if (depositAccountType.isRecurringDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((RecurringDepositProduct) product) .depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); final DepositProductRecurringDetail prodRecurringDetail = ((RecurringDepositProduct) product).depositRecurringDetail(); final DepositAccountRecurringDetail accountRecurringDetail = this.assembleAccountRecurringDetail(command, prodRecurringDetail.recurringDetail()); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountRecurringDetail, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(rdAccount); accountRecurringDetail.updateAccountReference(rdAccount); rdAccount.validateDomainRules(); account = rdAccount; } if (account != null) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(), depositAccountType.resourceName()); } return account; } public SavingsAccount assembleFrom(final Long savingsId, DepositAccountType depositAccountType) { final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId, depositAccountType); account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure .depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, productPreClosure); final DepositTermDetail updatedProductTerm = this.depositProductAssembler.assembleDepositTermDetail(command, productTerm); final BigDecimal depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName); final Integer depositPeriod = command.integerValueOfParameterNamed(depositPeriodParamName); final Integer depositPeriodFrequencyId = command.integerValueOfParameterNamed(depositPeriodFrequencyIdParamName); final SavingsPeriodFrequencyType depositPeriodFrequency = SavingsPeriodFrequencyType.fromInt(depositPeriodFrequencyId); final SavingsAccount account = null; final LocalDate expectedFirstDepositOnDate = command.localDateValueOfParameterNamed(expectedFirstDepositOnDateParamName); final Boolean trasferInterest = command.booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName); // calculate maturity amount final BigDecimal maturityAmount = null;// calculated and updated in // account final LocalDate maturityDate = null;// calculated and updated in account final DepositAccountOnClosureType accountOnClosureType = null; return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest); } public DepositAccountRecurringDetail assembleAccountRecurringDetail(final JsonCommand command, final DepositRecurringDetail prodRecurringDetail) { final BigDecimal recurringDepositAmount = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); boolean isMandatoryDeposit; boolean allowWithdrawal; boolean adjustAdvanceTowardsFuturePayments; boolean isCalendarInherited; if (command.parameterExists(isMandatoryDepositParamName)) { isMandatoryDeposit = command.booleanObjectValueOfParameterNamed(isMandatoryDepositParamName); } else { isMandatoryDeposit = prodRecurringDetail.isMandatoryDeposit(); } if (command.parameterExists(allowWithdrawalParamName)) { allowWithdrawal = command.booleanObjectValueOfParameterNamed(allowWithdrawalParamName); } else { allowWithdrawal = prodRecurringDetail.allowWithdrawal(); } if (command.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName)) { adjustAdvanceTowardsFuturePayments = command.booleanObjectValueOfParameterNamed(adjustAdvanceTowardsFuturePaymentsParamName); } else { adjustAdvanceTowardsFuturePayments = prodRecurringDetail.adjustAdvanceTowardsFuturePayments(); } if (command.parameterExists(isCalendarInheritedParamName)) { isCalendarInherited = command.booleanObjectValueOfParameterNamed(isCalendarInheritedParamName); } else { isCalendarInherited = false; } final DepositRecurringDetail depositRecurringDetail = DepositRecurringDetail.createFrom(isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments); final DepositAccountRecurringDetail depositAccountRecurringDetail = DepositAccountRecurringDetail.createNew(recurringDepositAmount, depositRecurringDetail, null, isCalendarInherited); return depositAccountRecurringDetail; } public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = this.fromApiJsonHelper.parse(json); final Collection savingsAccountTransactions = new ArrayList<>(); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale); if (element.isJsonObject()) { if (topLevelJsonElement.has(bulkSavingsDueTransactionsParamName) && topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); } final SavingsAccountTransactionDTO savingsAccountTransactionDTO = new SavingsAccountTransactionDTO(formatter, transactionDate, dueAmount, detail, new Date(), savingsId, user, depositAccountType); savingsAccountTransactions.add(savingsAccountTransactionDTO); } } } return savingsAccountTransactions; } private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { user = this.context.getAuthenticatedUserIfPresent(); } return user; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2661 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java/#L107-L472 | 1 | 248 | 2661 | major |
| 1526 | YES, I found bad smells. the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11186 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 1526 | 11186 | minor |
| 1895 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class SwiftUtils { public static final String READ = "read(buffer, offset, length)"; /** * Join two (non null) paths, inserting a forward slash between them * if needed * * @param path1 first path * @param path2 second path * @return the combined path */ public static String joinPaths(String path1, String path2) { StringBuilder result = new StringBuilder(path1.length() + path2.length() + 1); result.append(path1); boolean insertSlash = true; if (path1.endsWith("/")) { insertSlash = false; } else if (path2.startsWith("/")) { insertSlash = false; } if (insertSlash) { result.append("/"); } result.append(path2); return result.toString(); } /** * This test contains the is-directory logic for Swift, so if * changed there is only one place for it. * * @param fileStatus status to examine * @return true if we consider this status to be representative of a * directory. */ public static boolean isDirectory(FileStatus fileStatus) { return fileStatus.isDirectory() || isFilePretendingToBeDirectory(fileStatus); } /** * Test for the entry being a file that is treated as if it is a * directory * * @param fileStatus status * @return true if it meets the rules for being a directory */ public static boolean isFilePretendingToBeDirectory(FileStatus fileStatus) { return fileStatus.getLen() == 0; } /** * Predicate: Is a swift object referring to the root directory? * @param swiftObject object to probe * @return true iff the object refers to the root */ public static boolean isRootDir(SwiftObjectPath swiftObject) { return swiftObject.objectMatches("") || swiftObject.objectMatches("/"); } /** * Sprintf() to the log iff the log is at debug level. If the log * is not at debug level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void debug(Logger log, String text, Object... args) { if (log.isDebugEnabled()) { log.debug(String.format(text, args)); } } /** * Log an exception (in text and trace) iff the log is at debug * @param log Log to use * @param text text message * @param ex exception */ public static void debugEx(Logger log, String text, Exception ex) { if (log.isDebugEnabled()) { log.debug(text + ex, ex); } } /** * Sprintf() to the log iff the log is at trace level. If the log * is not at trace level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void trace(Logger log, String text, Object... args) { if (log.isTraceEnabled()) { log.trace(String.format(text, args)); } } /** * Given a partition number, calculate the partition value. * This is used in the SwiftNativeOutputStream, and is placed * here for tests to be able to calculate the filename of * a partition. * @param partNumber part number * @return a string to use as the filename */ public static String partitionFilenameFromNumber(int partNumber) { return String.format("%06d", partNumber); } /** * List a a path to string * @param fileSystem filesystem * @param path directory * @return a listing of the filestatuses of elements in the directory, one * to a line, preceded by the full path of the directory * @throws IOException connectivity problems */ public static String ls(FileSystem fileSystem, Path path) throws IOException { if (path == null) { //surfaces when someone calls getParent() on something at the top of the path return "/"; } FileStatus[] stats; String pathtext = "ls " + path; try { stats = fileSystem.listStatus(path); } catch (FileNotFoundException e) { return pathtext + " -file not found"; } catch (IOException e) { return pathtext + " -failed: " + e; } return pathtext + fileStatsToString(stats, "\n"); } /** * Take an array of filestatus and convert to a string (prefixed w/ a [01] counter * @param stats array of stats * @param separator separator after every entry * @return a stringified set */ public static String fileStatsToString(FileStatus[] stats, String separator) { StringBuilder buf = new StringBuilder(stats.length * 128); for (int i = 0; i < stats.length; i++) { buf.append(String.format("[%02d] %s", i, stats[i])).append(separator); } return buf.toString(); } /** * Verify that the basic args to a read operation are valid; * throws an exception if not -with meaningful text including * @param buffer destination buffer * @param off offset * @param len number of bytes to read * @throws NullPointerException null buffer * @throws IndexOutOfBoundsException on any invalid range. */ public static void validateReadArgs(byte[] buffer, int off, int len) { if (buffer == null) { throw new NullPointerException("Null byte array in"+ READ); } if (off < 0 ) { throw new IndexOutOfBoundsException("Negative buffer offset " + off + " in " + READ); } if (len < 0 ) { throw new IndexOutOfBoundsException("Negative read length " + len + " in " + READ); } if (off > buffer.length) { throw new IndexOutOfBoundsException("Buffer offset of " + off + "beyond buffer size of " + buffer.length + " in " + READ); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12333 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-openstack/src/main/java/org/apache/hadoop/fs/swift/util/SwiftUtils.java/#L32-L216 | 2 | 1895 | 12333 | minor |
| 1530 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11205 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 2 | 1530 | 11205 | major |
| 649 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6382 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 1 | 649 | 6382 | major |
| 2560 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14836 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 | 1 | 2560 | 14836 | minor |
| 348 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TraversalFieldAccessorFactory implements FieldAccessorFactory { @Override public boolean accept(final Neo4JPersistentProperty f) { final GraphTraversal graphEntityTraversal = f.getAnnotation(GraphTraversal.class); return graphEntityTraversal != null && graphEntityTraversal.traversalBuilder() != FieldTraversalDescriptionBuilder.class && f.getType().equals(Iterable.class); } @Override public FieldAccessor forField(final Neo4JPersistentProperty property) { return new TraversalFieldAccessor(property); } /** * @author Michael Hunger * @since 12.09.2010 */ public static class TraversalFieldAccessor implements FieldAccessor { protected final Neo4JPersistentProperty property; private final FieldTraversalDescriptionBuilder fieldTraversalDescriptionBuilder; private Class target; protected String[] params; public TraversalFieldAccessor(final Neo4JPersistentProperty property) { this.property = property; final GraphTraversal graphEntityTraversal = property.getAnnotation(GraphTraversal.class); this.target = resolveTarget(graphEntityTraversal,property); this.params = graphEntityTraversal.params(); this.fieldTraversalDescriptionBuilder = createTraversalDescription(graphEntityTraversal); } private Class resolveTarget(GraphTraversal graphTraversal, Neo4JPersistentProperty property) { if (!graphTraversal.elementClass().equals(NodeBacked.class)) return graphTraversal.elementClass(); final Class result = property.getTypeInformation().getActualType().getType(); Class[] allowedTypes={NodeBacked.class,RelationshipBacked.class,Node.class,Relationship.class, Path.class}; if (!checkTypes(result,allowedTypes)) throw new IllegalArgumentException("The target result type "+result+" of the traversal is no subclass of the allowed types: "+property+" "+allowedTypes); return result; } private boolean checkTypes(Class target, Class...allowedTypes) { for (Class type : allowedTypes) { if (type.isAssignableFrom(target)) return true; } return false; } @Override public boolean isWriteable(NodeBacked nodeBacked) { return false; } @Override public Object setValue(final NodeBacked nodeBacked, final Object newVal) { throw new InvalidDataAccessApiUsageException("Cannot set readonly traversal description field " + property); } @Override public Object getValue(final NodeBacked nodeBacked) { final TraversalDescription traversalDescription = fieldTraversalDescriptionBuilder.build(nodeBacked, property,params); return doReturn(nodeBacked.findAllByTraversal(target, traversalDescription)); } private FieldTraversalDescriptionBuilder createTraversalDescription(final GraphTraversal graphEntityTraversal) { try { final Class traversalDescriptionClass = graphEntityTraversal.traversalBuilder(); final Constructor constructor = traversalDescriptionClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating TraversalDescription from " + property,e); } } @Override public Object getDefaultImplementation() { return null; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 3559 | https://github.com/spring-projects/spring-data-graph/blob/0210210ce436eb83bf200f5d5f9a63a440c5b27a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/fieldaccess/TraversalFieldAccessorFactory.java/#L36-L119 | 1 | 348 | 3559 | minor |
| 2415 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | data class | t | t | f | data class | blob | 0 | 14419 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 2415 | 14419 | minor |
| 2624 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15072 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 2624 | 15072 | minor |
| 994 | YES I found bad smells. The bad smells are: 1. Long method 2. Class not following proper naming convention 3. Code duplication 4. Feature envy 5. Use of instanceof operator 6. Complex conditional statements 7. Magic numbers (the use of hardcoded values) 8. Poor code readability and maintenance | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static final class SymbolComparator implements Comparator { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object arg0, Object arg1) { long addr0=0; long addr1=0; // arg0 and arg1 will be Symbol objects if (arg0 instanceof Symbol) { Symbol S0 = (Symbol) arg0; Symbol S1 = (Symbol) arg1; addr0 = S0.symbolStart; addr1 = S1.symbolStart; } else { addr0 = ((Long)arg0).longValue(); addr1 = ((Long)arg1).longValue(); } // both +ve if (addr0 >= 0 && addr1 >=0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return -1; return 1; } // both -ve if (addr0 < 0 && addr1 < 0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return 1; return -1; } if (addr0 < 0 && addr1 >=0) { return 1; } return -1; } } |
blob | Long method2 Class not following proper naming convention3 Code duplication4 Feature envy5 Use of instanceof operator6 Complex conditional statements7 Magic numbers (the use of hardcoded values)8 Poor code readability and maintenance | t | f | f | . Long method2. Class not following proper naming convention3. Code duplication4. Feature envy5. Use of instanceof operator6. Complex conditional statements7. Magic numbers (the use of hardcoded values)8. Poor code readability and maintenance | blob | 0 | 9091 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/Symbol.java/#L134-L175 | 2 | 994 | 9091 | minor |
| 778 | YES, I found bad smells: 1. Long method 2. Duplicate code 3. Shotgun surgery 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class TomcatInjections { // load when needed private TomcatInjections() { // no-op } private static Map> buildInjectionMap(final NamingResourcesImpl namingResources) { final Map> injectionMap = new HashMap<>(); for (final Injectable resource : namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (final Injectable resource : namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private static void addInjectionTarget(final Injectable resource, final Map> injectionMap) { final List injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && !injectionTargets.isEmpty()) { final String jndiName = resource.getName(); for (final InjectionTarget injectionTarget : injectionTargets) { final String clazz = injectionTarget.getTargetClass(); Map injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } } |
blob | Long method2 Duplicate code3 Shotgun surgery4 Feature envy | t | f | f | . Long method2. Duplicate code3. Shotgun surgery4. Feature envy | blob | 0 | 7445 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/JavaeeInstanceManager.java/#L316-L362 | 2 | 778 | 7445 | minor |
| 1000 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | data class | t | t | f | data class | long method | 0 | 9174 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 1000 | 9174 | major |
| 149 | {"message": "YES, I found bad smells", "bad smells are:": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class OgnlHelper { private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); private OgnlHelper() { } /** * Tests whether or not the given String is a Camel OGNL expression. * * An expression is considered an OGNL expression when it contains either one of the following chars: . or [ * * @param expression the String * @return true if a Camel OGNL expression, otherwise false. */ public static boolean isValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } // the brackets should come in a pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 && bracketEnd > 0) { return bracketBegin == bracketEnd; } return expression.contains("."); } public static boolean isInvalidValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) { return false; } // the brackets should come in pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 || bracketEnd > 0) { return bracketBegin != bracketEnd; } // check for double dots if (expression.contains("..")) { return true; } return false; } /** * Validates whether the method name is using valid java identifiers in the name * Will throw {@link IllegalArgumentException} if the method name is invalid. */ public static void validateMethodName(String method) { if (ObjectHelper.isEmpty(method)) { return; } for (int i = 0; i < method.length(); i++) { char ch = method.charAt(i); if (i == 0 && '.' == ch) { // its a dot before a method name continue; } if (ch == '(' || ch == '[' || ch == '.' || ch == '?') { // break when method name ends and sub method or arguments begin break; } if (i == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method); } } } /** * Tests whether or not the given Camel OGNL expression is using the null safe operator or not. * * @param ognlExpression the Camel OGNL expression * @return true if the null safe operator is used, otherwise false. */ public static boolean isNullSafeOperator(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return false; } return ognlExpression.startsWith("?"); } /** * Removes any leading operators from the Camel OGNL expression. * * Will remove any leading of the following chars: ? or . * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any leading operators. */ public static String removeLeadingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.startsWith("?")) { ognlExpression = ognlExpression.substring(1); } if (ognlExpression.startsWith(".")) { ognlExpression = ognlExpression.substring(1); } return ognlExpression; } /** * Removes any trailing operators from the Camel OGNL expression. * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any trailing operators. */ public static String removeTrailingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.contains("[")) { return StringHelper.before(ognlExpression, "["); } return ognlExpression; } public static String removeOperators(String ognlExpression) { return removeLeadingOperators(removeTrailingOperators(ognlExpression)); } public static KeyValueHolder isOgnlIndex(String ognlExpression) { Matcher matcher = INDEX_PATTERN.matcher(ognlExpression); if (matcher.matches()) { // to avoid empty strings as we want key/value to be null in such cases String key = matcher.group(1); if (ObjectHelper.isEmpty(key)) { key = null; } // to avoid empty strings as we want key/value to be null in such cases String value = matcher.group(2); if (ObjectHelper.isEmpty(value)) { value = null; } return new KeyValueHolder<>(key, value); } return null; } /** * Regular expression with repeating groups is a pain to get right * and then nobody understands the reg exp afterwards. * So we use a bit ugly/low-level Java code to split the OGNL into methods. * * @param ognl the ognl expression * @return a list of methods, will return an empty list, if ognl expression has no methods * @throws IllegalArgumentException if the last method has a missing ending parenthesis */ public static List splitOgnl(String ognl) { List methods = new ArrayList<>(); // return an empty list if ognl is empty if (ObjectHelper.isEmpty(ognl)) { return methods; } StringBuilder sb = new StringBuilder(); int j = 0; // j is used as counter per method boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo] boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo}) for (int i = 0; i < ognl.length(); i++) { char ch = ognl.charAt(i); // special for starting a new method if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?') || (ch != '.' && ch != '?' && ch != ']')) { sb.append(ch); // special if we are doing square bracket if (ch == '[' && !parenthesisBracket) { squareBracket = true; } else if (ch == '(') { parenthesisBracket = true; } else if (ch == ')') { parenthesisBracket = false; } j++; // advance } else { if (ch == '.' && !squareBracket && !parenthesisBracket) { // only treat dot as a method separator if not inside a square bracket block // as dots can be used in key names when accessing maps // a dit denotes end of this method and a new method is to be invoked String s = sb.toString(); // reset sb sb.setLength(0); // pass over ? to the new method if (s.endsWith("?")) { sb.append("?"); s = s.substring(0, s.length() - 1); } // add the method methods.add(s); // reset j to begin a new method j = 0; } else if (ch == ']' && !parenthesisBracket) { // append ending ] to method name sb.append(ch); String s = sb.toString(); // reset sb sb.setLength(0); // add the method methods.add(s); // reset j to begin a new method j = 0; // no more square bracket squareBracket = false; } // and don't lose the char if its not an ] end marker (as we already added that) if (ch != ']' || parenthesisBracket) { sb.append(ch); } // only advance if already begun on the new method if (j > 0) { j++; } } } // add remainder in buffer when reached end of data if (sb.length() > 0) { methods.add(sb.toString()); } String last = methods.isEmpty() ? null : methods.get(methods.size() - 1); if (parenthesisBracket && last != null) { // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis if (last.contains("(") && !last.endsWith(")")) { throw new IllegalArgumentException("Method should end with parenthesis, was " + last); } } return methods; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1873 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-util/src/main/java/org/apache/camel/util/OgnlHelper.java/#L27-L292 | 2 | 149 | 1873 | major |
| 159 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class AssignmentTask implements Runnable { final Map> assignmentFailures; HostAndPort location; private Map> assignmentsPerTablet; public AssignmentTask(Map> assignmentFailures, String location, Map> assignmentsPerTablet) { this.assignmentFailures = assignmentFailures; this.location = HostAndPort.fromString(location); this.assignmentsPerTablet = assignmentsPerTablet; } private void handleFailures(Collection failures, String message) { for (KeyExtent ke : failures) { List mapFiles = assignmentsPerTablet.get(ke); synchronized (assignmentFailures) { for (PathSize pathSize : mapFiles) { List existingFailures = assignmentFailures.get(pathSize.path); if (existingFailures == null) { existingFailures = new ArrayList<>(); assignmentFailures.put(pathSize.path, existingFailures); } existingFailures.add(ke); } } log.info("Could not assign {} map files to tablet {} because : {}. Will retry ...", mapFiles.size(), ke, message); } } @Override public void run() { HashSet uniqMapFiles = new HashSet<>(); for (List mapFiles : assignmentsPerTablet.values()) for (PathSize ps : mapFiles) uniqMapFiles.add(ps.path); log.debug("Assigning {} map files to {} tablets at {}", uniqMapFiles.size(), assignmentsPerTablet.size(), location); try { List failures = assignMapFiles(context, location, assignmentsPerTablet); handleFailures(failures, "Not Serving Tablet"); } catch (AccumuloException | AccumuloSecurityException e) { handleFailures(assignmentsPerTablet.keySet(), e.getMessage()); } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 1984 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/client/BulkImporter.java/#L449-L499 | 1 | 159 | 1984 | minor |
| 1725 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DimsDataList implements Serializable { /** * */ private static final long serialVersionUID = -5902704017223885965L; private List dimsData; private boolean expression; public DimsDataList() { } public DimsDataList(List chunk) { dimsData = chunk; } public DimsDataList(int[] dataShape) throws Exception { try { // For now we just assume the first dimensions are the slow ones to make an axis out // of. Later read the axis from the meta list but we do not have examples of this so // far. int xaxis=-1,yaxis=-1; for (int i = 0; i=0; i--) { if (dataShape[i]>1) { if (yaxis<0) { getDimsData(i).setPlotAxis(AxisType.Y); yaxis = i; continue; } else if (xaxis<0) { getDimsData(i).setPlotAxis(AxisType.X); xaxis = i; continue; } } } // If we only found a y it may be a multiple-dimension set with only 1D possible. // In that case change y to x. if (yaxis>-1 && xaxis<0) { getDimsData(yaxis).setPlotAxis(AxisType.X); } } finally { //file.close(); } } public Iterable iterable() { return dimsData; } public void add(DimsData dimension) { if (dimsData==null) dimsData = new ArrayList(3); if (dimsData.size()>dimension.getDimension() && dimension.getDimension()>-1) { dimsData.set(dimension.getDimension(), dimension); } else { dimsData.add(dimension); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dimsData == null) ? 0 : dimsData.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DimsDataList other = (DimsDataList) obj; if (dimsData == null) { if (other.dimsData != null) return false; } else if (!dimsData.equals(other.dimsData)) return false; return true; } public static Object[] getDefault() { return new DimsData[]{new DimsData(0)}; } public Object[] getElements() { if (dimsData==null) return null; return dimsData.toArray(new DimsData[dimsData.size()]); } public int size() { if (dimsData==null) return 0; return dimsData.size(); } public DimsData getDimsData(int i) { if (dimsData==null) return null; return dimsData.get(i); } public Iterator iterator() { if (dimsData==null) return null; return dimsData.iterator(); } public void clear() { if (dimsData!=null) dimsData.clear(); } public String toString() { return toString(null); } public String toString(int[] shape) { final StringBuilder buf = new StringBuilder(); buf.append("[ "); int index = 0; for (DimsData d : dimsData) { final int upper = shape!=null ? shape[index] : -1; buf.append(d.getUserString(upper)); if (d!=dimsData.get(dimsData.size()-1)) buf.append(", "); ++index; } buf.append(" ]"); return buf.toString(); } public boolean isRangeDefined() { for (DimsData data : iterable()) { if (data.getSliceRange()!=null) return true; } return false; } public int getAxisCount() { if (dimsData==null) return -1; int count = 0; for (DimsData dd : dimsData) { if (!dd.getPlotAxis().hasValue()) count++; } return count; } public int getRangeCount() { int count = 0; for (DimsData dd : dimsData) { if (dd.getPlotAxis()==AxisType.RANGE) count++; } return count; } public boolean is2D() { return getAxisCount()==2; } public DimsDataList clone() { final DimsDataList clone = new DimsDataList(); for (DimsData dd : iterable()) { DimsData dnew = dd.clone(); clone.add(dnew); } clone.expression = expression; return clone; } /** * Sets any axes there are to the axis passed in */ public void normalise(AxisType axis) { for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) dd.setPlotAxis(axis); } } /** * Probably not best algorithm but we are dealing with very small arrays here. * This is simply trying to ensure that only one dimension is selected as an * axis because the plot has changed. * * @param iaxisToFind */ public void setSingleAxisOnly(AxisType iaxisToFind, AxisType iaxisValue) { DimsData found = null; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==iaxisToFind) { dd.setPlotAxis(iaxisValue); found=dd; } } if (found!=null) { for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is x for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) { dd.setPlotAxis(iaxisValue); found=dd; } } for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis */ public void setTwoAxesOnly(AxisType firstAxis, AxisType secondAxis) { boolean foundFirst = false, foundSecond = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; } if (foundFirst&&foundSecond) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis * @param thirdAxis */ public void setThreeAxesOnly(AxisType firstAxis, AxisType secondAxis, AxisType thirdAxis) { boolean foundFirst = false, foundSecond = false, foundThird = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; if (dd.getPlotAxis()==thirdAxis) foundThird = true; } if (foundFirst&&foundSecond&&foundThird) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis, thirdAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis, thirdAxis); if (!foundThird) foundThird = processAxis(thirdAxis, firstAxis, secondAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } private final boolean processAxis(AxisType axis, AxisType... ignoredAxes) { final List ignored = asList(ignoredAxes); for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue() && !ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } for (DimsData dd : iterable()) { if (!ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } return false; } /** * Convert a primitive array to a list. * @param array - an array of primitives * @return */ @SuppressWarnings("unchecked") private static final List asList(final Object array) { if (!array.getClass().isArray()) throw new IllegalArgumentException("Not an array"); return new AbstractList() { @Override public T get(int index) { return (T) Array.get(array, index); } @Override public int size() { return Array.getLength(array); } }; } public boolean isXFirst() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().hasValue()) continue; return dd.getPlotAxis()==AxisType.X; } return false; } public void reverseImage() { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==AxisType.X) { dd.setPlotAxis(AxisType.Y); continue; } if (dd.getPlotAxis()==AxisType.Y) { dd.setPlotAxis(AxisType.X); continue; } } } public boolean isExpression() { return expression; } public void setExpression(boolean expression) { this.expression = expression; } public boolean isEmpty() { return dimsData==null || dimsData.isEmpty(); } public boolean isAdvanced() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().isAdvanced()) return true; } return false; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public List getDimsData() { return dimsData; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public void setDimsData(List dimsData) { this.dimsData = dimsData; } public void removeLargeStacks(ISliceSystem slicingSystem, int maxStack) { for (DimsData dd : getDimsData()) { if (dd.getPlotAxis().isStack(slicingSystem)) { if (dd.getSliceRange(true)==null || "".equals(dd.getSliceRange(true)) || "all".equals(dd.getSliceRange(true))) { final ILazyDataset lz = slicingSystem.getData().getLazySet(); if (lz!=null) { final int size = lz.getShape()[dd.getDimension()]; if (size>=maxStack) { // We set a default slice dd.setSliceRange("0:25"); } } } } } } public Slice[] toSliceArray(int[] dataShape) { final Slice[] ret = new Slice[size()]; for (int i = 0; i < size(); i++) { DimsData dd = getDimsData(i); if (dd.isSlice()) { ret[i] = new Slice(dd.getSlice(), dd.getSlice()+1); } else { ret[i] = new Slice(dataShape[dd.getDimension()]); } } return ret; } /** * Export to Map from DimsDataList * @return */ public Map toMap() { final Map ret = new HashMap(size()); for (DimsData dd : iterable()) { if (dd.isSlice()) { ret.put(dd.getDimension(), String.valueOf(dd.getSlice())); } else if (dd.isTextRange()) { ret.put(dd.getDimension(), dd.getSliceRange()!=null ? dd.getSliceRange() : "all"); } else if ( dd.getPlotAxis()!=null){ ret.put(dd.getDimension(), dd.getPlotAxis().getName()); } } return ret; } /** * Set the current DimsDataList to what is defined in the pass in map. * @param map * @param shape */ public void fromMap(Map map, int[] shape) { clear(); for (int i = 0; i < shape.length; i++) { add(new DimsData(i)); } if (map.isEmpty()) { // Make one up getDimsData(0).setSliceRange("all"); if (size()==2) { getDimsData(1).setPlotAxis(AxisType.X); } else if (size()>2) { getDimsData(1).setPlotAxis(AxisType.Y); getDimsData(2).setPlotAxis(AxisType.X); for (int i = 3; i < size(); i++) { getDimsData(i).setSlice(0); } } } else { // Init one from map saved int dim = 0; for (DimsData dd : iterable()) { String value = map.get(dd.getDimension()); if (value==null) value = map.get(String.valueOf(dd.getDimension())); if (value!=null) { if ("all".equals(value)) { dd.setPlotAxis(AxisType.RANGE); continue; } AxisType at = AxisType.forLabel(value); if (at!=null) { dd.setPlotAxis(at); continue; } try { dd.setSlice(Integer.parseInt(value)); } catch (Exception ne) { dd.setSliceRange(value); } } else { AxisType type = AxisType.forAxis(dim); dd.setPlotAxis(type); ++dim; } } } } } |
blob | long method | t | t | f | long method | blob | 0 | 11805 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.slicing.api/src/org/eclipse/dawnsci/slicing/api/system/DimsDataList.java/#L26-L549 | 1 | 1725 | 11805 | major |
| 1465 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11030 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 1 | 1465 | 11030 | major |
| 408 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4156 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 408 | 4156 | major |
| 120 | {"message": "YES I found bad smells the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1519 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 120 | 1519 | major |
| 1791 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11988 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 1791 | 11988 | minor |
| 1336 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | long method | t | t | f | long method | blob | 0 | 10727 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 1336 | 10727 | minor |
| 81 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1189 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 81 | 1189 | minor |
| 1448 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1. Data class" : "The class has only data attributes and getter/setter methods." }, { "2. Long Method" : "The methods writeAsElement and readFromElement are quite long and may need refactoring." } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
blob | 1. data class: the class has only data attributes and getter/setter methods., 2. long method: the methods writeaselement and readfromelement are quite long and may need refactoring. | t | t | f | 1. data class: the class has only data attributes and getter/setter methods., 2. long method: the methods writeaselement and readfromelement are quite long and may need refactoring. | blob | 0 | 10989 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 1448 | 10989 | minor |
| 1642 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells": [ "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | bad_smells, Long Method | t | f | f | bad_smells, Long Method | data class | 0 | 11545 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 1642 | 11545 | minor |
| 78 | {"message": "NO, I did not find any bad smell"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | f | f | f | data class | 0 | 1160 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 78 | 1160 | minor | ||
| 4100 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Magic numbers 5. Inconsistent naming conventions 6. Inefficient use of comments 7. Too many constants declared at the top of the class 8. Multiple unnecessary casts 9. Nested if statements 10. Unnecessary conditional statements in switch cases 11. Mixing of different responsibilities in methods (e.g. checking permissions and starting services) 12. Poor exception handling (e.g. using Toast to display error messages instead of proper exception handling) 13. Code duplication (e.g. unnecessary check against REQUEST_ENABLE_BT in onActivityResult and checkPermissions methods) 14. Use of deprecated methods 15. Inconsistent use of formatting (bracket placement, spacing) 16. Use of generic catch statements 17. Mixing of UI and business logic in the Activity class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_LOCATION = 1; private static final String NEARBY_BEACONS_FRAGMENT_TAG = "NearbyBeaconsFragmentTag"; private static final String SETTINGS_FRAGMENT_TAG = "SettingsFragmentTag"; private static final String BLOCKED_URLS_FRAGMENT_TAG = "BlockedUrlsFragmentTag"; private static final String ABOUT_FRAGMENT_TAG = "AboutFragmentTag"; private static final String DEMOS_FRAGMENT_TAG = "DemosFragmentTag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Utils.setSharedPreferencesDefaultValues(this); PermissionCheck.getInstance().setCheckingPermissions(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * Called when a menu item is tapped. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // If the about menu item was selected case R.id.action_about: showAboutFragment(); return true; // If the settings menu item was selected case R.id.action_settings: showSettingsFragment(); return true; case R.id.block_settings: showBlockedFragment(); return true; case R.id.action_demos: showDemosFragment(); return true; // If the action bar up button was pressed case android.R.id.home: getFragmentManager().popBackStack(); getActionBar().setDisplayHomeAsUpEnabled(false); } return super.onOptionsItemSelected(item); } /** * Ensures Bluetooth is available on the beacon and it is enabled. If not, * displays a dialog requesting user permission to enable Bluetooth. */ private void checkPermissions(BluetoothAdapter bluetoothAdapter) { // Acquire lock PermissionCheck.getInstance().setCheckingPermissions(true); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } ensureLocationPermissionIsEnabled(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == REQUEST_ENABLE_BT && resultCode == -1) { ensureLocationPermissionIsEnabled(); return; } Toast.makeText(this, getString(R.string.bt_on), Toast.LENGTH_LONG).show(); finish(); } private void ensureLocationPermissionIsEnabled() { if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } PermissionCheck.getInstance().setCheckingPermissions(false); finishLoad(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionCheck.getInstance().setCheckingPermissions(false); } else { Toast.makeText(getApplicationContext(), getString(R.string.loc_permission), Toast.LENGTH_LONG).show(); finish(); } break; } default: } } @Override protected void onResume() { super.onResume(); // Lock to prevent onResume from running until all permissions are granted if (!PermissionCheck.getInstance().isCheckingPermissions()) { Log.d(TAG, "resumed MainActivity"); BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = btManager != null ? btManager.getAdapter() : null; if (btAdapter == null) { Toast.makeText(getApplicationContext(), R.string.error_bluetooth_support, Toast.LENGTH_LONG).show(); finish(); return; } if (Utils.checkIfUserHasOptedIn(this)) { Log.d(TAG, "checkingPermissions"); checkPermissions(btAdapter); } else { // Show the oob activity Intent intent = new Intent(this, OobActivity.class); startActivity(intent); } } } private void finishLoad() { Intent intent = new Intent(this, ScreenListenerService.class); startService(intent); NearbyBeaconsFragment nearbyBeaconsFragment = (NearbyBeaconsFragment) getFragmentManager().findFragmentByTag(NEARBY_BEACONS_FRAGMENT_TAG); if (nearbyBeaconsFragment != null) { nearbyBeaconsFragment.restartScan(); } else { showFragment(new NearbyBeaconsFragment(), NEARBY_BEACONS_FRAGMENT_TAG, false); } } /** * Show the fragment to configure the app. */ private void showSettingsFragment() { showFragment(new SettingsFragment(), SETTINGS_FRAGMENT_TAG, true); } /** * Show the fragment displaying information about this application. */ private void showAboutFragment() { showFragment(new AboutFragment(), ABOUT_FRAGMENT_TAG, true); } /** * Show the fragment displaying the blocked URLs. */ private void showBlockedFragment() { showFragment(new BlockedFragment(), BLOCKED_URLS_FRAGMENT_TAG, true); } /** * Show the fragment displaying the demos. */ private void showDemosFragment() { showFragment(new DemosFragment(), DEMOS_FRAGMENT_TAG, true); } @SuppressLint("CommitTransaction") private void showFragment(Fragment newFragment, String fragmentTag, boolean addToBackStack) { FragmentTransaction transaction = getFragmentManager().beginTransaction() .setCustomAnimations( R.animator.fade_in_and_slide_up_fragment, R.animator.fade_out_fragment, R.animator.fade_in_activity, R.animator.fade_out_fragment) .replace(R.id.main_activity_container, newFragment, fragmentTag); if (addToBackStack) { transaction.addToBackStack(null); } transaction.commit(); } } |
blob | Long method2 Feature envy3 Primitive obsession4 Magic numbers5 Inconsistent naming conventions6 Inefficient use of comments7 Too many constants declared at the top of the class8 Multiple unnecessary casts9 Nested if statements | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Magic numbers5. Inconsistent naming conventions6. Inefficient use of comments7. Too many constants declared at the top of the class8. Multiple unnecessary casts9. Nested if statements | blob | 0 | 10801 | https://github.com/google/physical-web/blob/12604319e99b6d6dff451fc5a58a13a271f1dc7a/android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/MainActivity.java/#L39-L228 | 2 | 4100 | 10801 | major |
| 2503 | YES I found bad smells the bad smells are: 1. Private variable without getter and setter methods being used | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | Private variable without getter and setter methods being used | t | f | f | . Private variable without getter and setter methods being used | data class | 0 | 14665 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 2503 | 14665 | major |
| 1622 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11487 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 2 | 1622 | 11487 | minor |
| 2734 | of the above will apply, the code is too straightforward to be considered bad smells. NO, I did not find any bad smells: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 710 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L45156-L45191 | 2 | 2734 | 710 | major | ||
| 170 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | blob | t | t | f | blob | data class | 0 | 2035 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 170 | 2035 | major |
| 2618 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 15050 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 2618 | 15050 | minor |
| 77 | {"response": "YES I found bad smells, the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 1159 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 2 | 77 | 1159 | minor |
| 1867 | {"message": "YES I found bad smells", "bad smells are": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 12239 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 1867 | 12239 | minor |
| 84 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class MonoWhen extends Mono implements SourceProducer { final boolean delayError; final Publisher[] sources; final Iterable> sourcesIterable; MonoWhen(boolean delayError, Publisher... sources) { this.delayError = delayError; this.sources = Objects.requireNonNull(sources, "sources"); this.sourcesIterable = null; } MonoWhen(boolean delayError, Iterable> sourcesIterable) { this.delayError = delayError; this.sources = null; this.sourcesIterable = Objects.requireNonNull(sourcesIterable, "sourcesIterable"); } @SuppressWarnings("unchecked") @Nullable Mono whenAdditionalSource(Publisher source) { Publisher[] oldSources = sources; if (oldSources != null) { int oldLen = oldSources.length; Publisher[] newSources = new Publisher[oldLen + 1]; System.arraycopy(oldSources, 0, newSources, 0, oldLen); newSources[oldLen] = source; return new MonoWhen(delayError, newSources); } return null; } @SuppressWarnings("unchecked") @Override public void subscribe(CoreSubscriber actual) { Publisher[] a; int n = 0; if (sources != null) { a = sources; n = a.length; } else { a = new Publisher[8]; for (Publisher m : sourcesIterable) { if (n == a.length) { Publisher[] b = new Publisher[n + (n >> 2)]; System.arraycopy(a, 0, b, 0, n); a = b; } a[n++] = m; } } if (n == 0) { Operators.complete(actual); return; } WhenCoordinator parent = new WhenCoordinator(actual, n, delayError); actual.onSubscribe(parent); parent.subscribe(a); } @Override public Object scanUnsafe(Attr key) { if (key == Attr.DELAY_ERROR) return delayError; return null; } static final class WhenCoordinator extends Operators.MonoSubscriber { final WhenInner[] subscribers; final boolean delayError; volatile int done; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater DONE = AtomicIntegerFieldUpdater.newUpdater(WhenCoordinator.class, "done"); @SuppressWarnings("unchecked") WhenCoordinator(CoreSubscriber subscriber, int n, boolean delayError) { super(subscriber); this.delayError = delayError; subscribers = new WhenInner[n]; for (int i = 0; i < n; i++) { subscribers[i] = new WhenInner(this); } } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.TERMINATED) { return done == subscribers.length; } if (key == Attr.BUFFERED) { return subscribers.length; } if (key == Attr.DELAY_ERROR) { return delayError; } return super.scanUnsafe(key); } @Override public Stream inners() { return Stream.of(subscribers); } void subscribe(Publisher[] sources) { WhenInner[] a = subscribers; for (int i = 0; i < a.length; i++) { sources[i].subscribe(a[i]); } } void signalError(Throwable t) { if (delayError) { signal(); } else { int n = subscribers.length; if (DONE.getAndSet(this, n) != n) { cancel(); actual.onError(t); } } } @SuppressWarnings("unchecked") void signal() { WhenInner[] a = subscribers; int n = a.length; if (DONE.incrementAndGet(this) != n) { return; } Throwable error = null; Throwable compositeError = null; for (int i = 0; i < a.length; i++) { WhenInner m = a[i]; Throwable e = m.error; if (e != null) { if (compositeError != null) { //this is ok as the composite created below is never a singleton compositeError.addSuppressed(e); } else if (error != null) { compositeError = Exceptions.multiple(error, e); } else { error = e; } } } if (compositeError != null) { actual.onError(compositeError); } else if (error != null) { actual.onError(error); } else { actual.onComplete(); } } @Override public void cancel() { if (!isCancelled()) { super.cancel(); for (WhenInner ms : subscribers) { ms.cancel(); } } } } static final class WhenInner implements InnerConsumer { final WhenCoordinator parent; volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater S = AtomicReferenceFieldUpdater.newUpdater(WhenInner.class, Subscription.class, "s"); Throwable error; WhenInner(WhenCoordinator parent) { this.parent = parent; } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.CANCELLED) { return s == Operators.cancelledSubscription(); } if (key == Attr.PARENT) { return s; } if (key == Attr.ACTUAL) { return parent; } if (key == Attr.ERROR) { return error; } return null; } @Override public Context currentContext() { return parent.currentContext(); } @Override public void onSubscribe(Subscription s) { if (Operators.setOnce(S, this, s)) { s.request(Long.MAX_VALUE); } else { s.cancel(); } } @Override public void onNext(Object t) { } @Override public void onError(Throwable t) { error = t; parent.signalError(t); } @Override public void onComplete() { parent.signal(); } void cancel() { Operators.terminate(S, this); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 1201 | https://github.com/reactor/reactor-core/blob/3958e2fabf49e16229dda5df39e7cde46797ec51/reactor-core/src/main/java/reactor/core/publisher/MonoWhen.java/#L36-L292 | 1 | 84 | 1201 | major |
| 5325 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | f | f | f | long method | 0 | 14949 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 5325 | 14949 | major | ||
| 1995 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12696 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 1995 | 12696 | minor |
| 4535 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw | t | f | f | . Long method2. Feature envy - the toString(), hashCode(), and equals() methods are duplicated from the Object class, indicating a possible design flaw. | data class | 0 | 12036 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 4535 | 12036 | minor |
| 2209 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13518 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 2209 | 13518 | minor |
| 1809 | {"message": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | t | f | f | long method | 0 | 12052 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 1809 | 12052 | minor | ||
| 1877 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12265 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 1877 | 12265 | critical |
| 2538 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 14768 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 1 | 2538 | 14768 | minor |
| 2585 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code. Similarly, there is duplicated code in the setter methods. 4. Too many parameters - the constructor and some methods have a lot of parameters passed in. 5. Magic numbers - there are multiple instances where numbers like 10000, 30000, and 16 are used without clear explanation. 6. Inconsistent naming - some variables are named with camel case, while others use underscores. 7. Excessive comments - many of the comments are redundant and add little value to the code. 8. Complex conditionals - some of the if statements contain complex conditions that may be hard to understand and maintain. 9. Inconsistent formatting - there are inconsistencies in formatting, such as uneven indentation. 10. Poor exception handling - in the copy method, an unchecked exception is thrown, which can lead to unexpected behavior. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Long method2 Feature envy3 Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code Similarly, there is duplicated code in the setter methods4 Too many parameters - the constructor and some methods have a lot of parameters passed in5 Magic numbers - there are multiple instances where numbers like | t | f | f | . Long method2. Feature envy3. Duplicated code - the getProtocol(), getHost(), and isSync() methods are all used to check different variables but have very similar code. Similarly, there is duplicated code in the setter methods.4. Too many parameters - the constructor and some methods have a lot of parameters passed in.5. Magic numbers - there are multiple instances where numbers like | data class | 0 | 14976 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 2585 | 14976 | major |
| 5046 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14099 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 1 | 5046 | 14099 | major |
| 799 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } } |
blob | long method | t | t | f | long method | blob | 0 | 7571 | https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/.mvn/wrapper/MavenWrapperDownloader.java/#L25-L110 | 1 | 799 | 7571 | minor |
| 151 | {"message": "YES, I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1911 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 151 | 1911 | major |
| 3803 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 9644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 3803 | 9644 | minor |
| 2653 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 15178 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2653 | 15178 | major |
| 480 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 4632 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 1 | 480 | 4632 | minor |
| 613 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6167 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 | 1 | 613 | 6167 | major |
| 2602 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 15022 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 2 | 2602 | 15022 | minor |
| 1781 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | t | f | f | long method | 0 | 11962 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 1 | 1781 | 11962 | minor | ||
| 1762 | YES I found bad smellsThe bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Inconsistent naming conventions 5. Use of primitive obsession 6. Use of null checks 7. Lack of proper exception handling 8. Lazy initialization of data structures 9. Use of raw types and unchecked assignments 10. Improper use of access modifiers 11. Confusing method signatures and parameter names 12. Improper indentation and formatting 13. Lack of documentation and comments 14. Poor naming choices for class and variable names. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } } |
blob | Long method2 Duplicate code3 Feature envy4 Inconsistent naming conventions5 Use of primitive obsession6 Use of null checks7 Lack of proper exception handling8 Lazy initialization of data structures9 Use of raw types and unchecked assignments | t | f | f | . Long method2. Duplicate code3. Feature envy4. Inconsistent naming conventions5. Use of primitive obsession6. Use of null checks7. Lack of proper exception handling8. Lazy initialization of data structures9. Use of raw types and unchecked assignments | blob | 0 | 11892 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 | 2 | 1762 | 11892 | minor |
| 268 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | f | f | f | data class | 0 | 2887 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 268 | 2887 | minor | |||
| 301 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3155 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 301 | 3155 | major |
| 2394 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14371 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 1 | 2394 | 14371 | major |
| 823 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
blob | long method | t | t | f | long method | blob | 0 | 7702 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 1 | 823 | 7702 | minor |
| 274 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2936 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 274 | 2936 | critical | ||
| 939 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 8450 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 939 | 8450 | major |
| 840 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 7789 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 840 | 7789 | minor |
| 1935 | YES I found bad smells - Thanks for asking, however, as specified in the instructions, I am not allowed to describe the smells, just list them. Please start your list with "the bad smells are:". the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 12464 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 1935 | 12464 | major |
| 726 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 6846 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 726 | 6846 | major |
| 2382 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14339 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 2 | 2382 | 14339 | minor |
| 862 | "YES I found bad smells" the bad smells are: 1. Inconsistent naming conventions (e.g. "indexingBase" and "minTaskId" - should either both use camelCase or both use underscores) 2. Long method (lots of code within each method) 3. Feature envy (the "tryTransferLocal" method is accessing and manipulating data from the WorkerState object, implying it should be a method within that class instead of ExecutorTransfer) 4. Data clumps (the "indexingBase" and "localReceiveQueues" variables are often used together and could potentially be combined into a data structure) 5. Obsolete comment (the comment above the "initLocalRecvQueues" method is incorrect as it is no longer the only method in the class) 6. Magic numbers (e.g. the use of "-1" and "-indexingBase" without explanation) 7. Possible violation of single responsibility principle (the "ExecutorTransfer" class has a mix of methods related to initialization and message transfer) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExecutorTransfer { private static final Logger LOG = LoggerFactory.getLogger(ExecutorTransfer.class); private final WorkerState workerData; private final KryoTupleSerializer serializer; private final boolean isDebug; private int indexingBase = 0; private ArrayList localReceiveQueues; // [taskId-indexingBase] => queue : List of all recvQs local to this worker private AtomicReferenceArray queuesToFlush; // [taskId-indexingBase] => queue, some entries can be null. : outbound Qs for this executor instance public ExecutorTransfer(WorkerState workerData, Map topoConf) { this.workerData = workerData; this.serializer = new KryoTupleSerializer(topoConf, workerData.getWorkerTopologyContext()); this.isDebug = ObjectReader.getBoolean(topoConf.get(Config.TOPOLOGY_DEBUG), false); } // to be called after all Executor objects in the worker are created and before this object is used public void initLocalRecvQueues() { Integer minTaskId = workerData.getLocalReceiveQueues().keySet().stream().min(Integer::compareTo).get(); this.localReceiveQueues = Utils.convertToArray(workerData.getLocalReceiveQueues(), minTaskId); this.indexingBase = minTaskId; this.queuesToFlush = new AtomicReferenceArray(localReceiveQueues.size()); } // adds addressedTuple to destination Q if it is not full. else adds to pendingEmits (if its not null) public boolean tryTransfer(AddressedTuple addressedTuple, Queue pendingEmits) { if (isDebug) { LOG.info("TRANSFERRING tuple {}", addressedTuple); } JCQueue localQueue = getLocalQueue(addressedTuple); if (localQueue != null) { return tryTransferLocal(addressedTuple, localQueue, pendingEmits); } return workerData.tryTransferRemote(addressedTuple, pendingEmits, serializer); } // flushes local and remote messages public void flush() throws InterruptedException { flushLocal(); workerData.flushRemotes(); } private void flushLocal() throws InterruptedException { for (int i = 0; i < queuesToFlush.length(); i++) { JCQueue q = queuesToFlush.get(i); if (q != null) { q.flush(); queuesToFlush.set(i, null); } } } public JCQueue getLocalQueue(AddressedTuple tuple) { if ((tuple.dest - indexingBase) >= localReceiveQueues.size()) { return null; } return localReceiveQueues.get(tuple.dest - indexingBase); } /** * Adds tuple to localQueue (if overflow is empty). If localQueue is full adds to pendingEmits instead. pendingEmits can be null. * Returns false if unable to add to localQueue. */ public boolean tryTransferLocal(AddressedTuple tuple, JCQueue localQueue, Queue pendingEmits) { workerData.checkSerialize(serializer, tuple); if (pendingEmits != null) { if (pendingEmits.isEmpty() && localQueue.tryPublish(tuple)) { queuesToFlush.set(tuple.dest - indexingBase, localQueue); return true; } else { pendingEmits.add(tuple); return false; } } else { return localQueue.tryPublish(tuple); } } } |
blob | Inconsistent naming conventions (eg "indexingBase" and "minTaskId" - should either both use camelCase or both use underscores) 2 Long method (lots of code within each method) 3 Feature envy (the "tryTransferLocal" method is accessing and manipulating data from the WorkerState object, implying it should be a method within that class instead of ExecutorTransfer) 4 Data clumps (the "indexingBase" and "localReceiveQueues" variables are often used together and could potentially be combined into a data structure) 5 Obsolete comment (the comment above the "initLocalRecvQueues" method is incorrect as it is no longer the only method in the class) 6 Magic numbers (eg the use of "- | t | f | f | . Inconsistent naming conventions (e.g. "indexingBase" and "minTaskId" - should either both use camelCase or both use underscores) 2. Long method (lots of code within each method) 3. Feature envy (the "tryTransferLocal" method is accessing and manipulating data from the WorkerState object, implying it should be a method within that class instead of ExecutorTransfer) 4. Data clumps (the "indexingBase" and "localReceiveQueues" variables are often used together and could potentially be combined into a data structure) 5. Obsolete comment (the comment above the "initLocalRecvQueues" method is incorrect as it is no longer the only method in the class) 6. Magic numbers (e.g. the use of "- | blob | 0 | 7911 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/executor/ExecutorTransfer.java/#L30-L113 | 2 | 862 | 7911 | minor |
| 1851 | { "output": "YES I found bad smells", "the bad smells are:": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | t | f | f | data class | 0 | 12190 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 1851 | 12190 | minor | ||
| 2408 | YES, I found bad smells The bad smells are: 1. Long class 2. Long constructor 3. Lack of encapsulation 4. Magic numbers/strings (i.e. 0, 0) 5. Long method 6. Feature envy 7. Inconsistent naming conventions (i.e. both get and set methods are named "readFrom") 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long class2 Long constructor3 Lack of encapsulation4 Magic numbers/strings (ie 0, 0)5 Long method6 Feature envy7 Inconsistent naming conventions (ie both get and set methods are named "readFrom")8 Lack of comments/documentation | t | f | f | . Long class2. Long constructor3. Lack of encapsulation4. Magic numbers/strings (i.e. 0, 0)5. Long method6. Feature envy7. Inconsistent naming conventions (i.e. both get and set methods are named "readFrom")8. Lack of comments/documentation | data class | 0 | 14390 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 2408 | 14390 | critical |
| 1291 | YES I found bad smells: 1. Getter and setter methods present for a single private field (code repetition). 2. Inconsistent use of annotations for the 'name' field. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Getter and setter methods present for a single private field (code repetition) 2 Inconsistent use of annotations for the 'name' field | t | f | f | . Getter and setter methods present for a single private field (code repetition). 2. Inconsistent use of annotations for the 'name' field. | data class | 0 | 10618 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 2 | 1291 | 10618 | critical |
| 1534 | { "output": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportsAwareClipboardAction extends TextEditorAction { public static class Factory implements IClipboardActionFactory { @Inject private MembersInjector injector; @Override public TextEditorAction create(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) { ImportsAwareClipboardAction action = new ImportsAwareClipboardAction(bundle, prefix, editor, operationCode); injector.injectMembers(action); return action; } } private static final XbaseClipboardTransfer TRANSFER_INSTANCE = new XbaseClipboardTransfer(); private final int operationCode; private ITextOperationTarget textOperationTarget; private @Inject ImportsUtil importsUtil; /** * Creates the action. * * @param bundle * the resource bundle * @param prefix * a prefix to be prepended to the various resource keys (described in ResourceAction * constructor), or null if none * @param editor * the text editor. May not be null. * @param operationCode * the operation code */ public ImportsAwareClipboardAction(ResourceBundle bundle, String prefix, ITextEditor editor, final int operationCode) { super(bundle, prefix, editor); this.operationCode = operationCode; if (operationCode == ITextOperationTarget.CUT) { setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); } else if (operationCode == ITextOperationTarget.COPY) { setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); } else if (operationCode == ITextOperationTarget.PASTE) { setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); } else { Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$ } update(); } protected void internalDoOperation() { if (operationCode == ITextOperationTarget.PASTE) { doPasteWithImportsOperation(); } else { doCutCopyWithImportsOperation(); } } private void doCutCopyWithImportsOperation() { try { final XbaseClipboardData cbData = createClipboardData(); if (cbData != null ) { ClipboardUtil.clipboardOperation(new Function() { @Override public Boolean apply(Clipboard clipboard) { Map payload = newLinkedHashMap(); payload.put(cbData, TRANSFER_INSTANCE); TextTransfer textTransfer = TextTransfer.getInstance(); String textData = (String) clipboard.getContents(textTransfer); if (textData == null || textData.isEmpty()) { // StyledText copied any data to ClipBoard return Boolean.FALSE; } payload.put(textData, textTransfer); RTFTransfer rtfTransfer = RTFTransfer.getInstance(); String rtfData = (String) clipboard.getContents(rtfTransfer); if (rtfData != null && !rtfData.isEmpty()) { payload.put(rtfData, rtfTransfer); } List datas = newArrayList(); List dataTypes = newArrayList(); for (Entry entry : payload.entrySet()) { datas.add(entry.getKey()); dataTypes.add(entry.getValue()); } try { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } return Boolean.FALSE; } } }); } } finally { textOperationTarget.doOperation(operationCode); } } private void doPasteWithImportsOperation() { XbaseClipboardData xbaseClipboardData = ClipboardUtil .clipboardOperation(new Function() { @Override public XbaseClipboardData apply(Clipboard input) { Object content = input.getContents(TRANSFER_INSTANCE); if (content instanceof XbaseClipboardData) { return (XbaseClipboardData) content; } return null; } }); JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent(); String textFromClipboard = ClipboardUtil.getTextFromClipboard(); XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor)); if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) { doPasteXbaseCode(xbaseClipboardData, addImports); } else if (javaImportsContent != null) { doPasteJavaCode(textFromClipboard, javaImportsContent, addImports); } else { textOperationTarget.doOperation(operationCode); } } /** * Should not add imports when pasting into a {@link XStringLiteral} or Comments (except of JavaDoc) * * @param document * - {@link IDocument} to work with * @param caretOffset * - current caret offset */ protected boolean shouldAddImports(IDocument document, int caretOffset) { if (caretOffset == 0) { return true; } String typeRight = IDocument.DEFAULT_CONTENT_TYPE; String typeLeft = IDocument.DEFAULT_CONTENT_TYPE; try { typeRight = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset, false); typeLeft = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset > 0 ? caretOffset - 1 : caretOffset, false); } catch (BadLocationException exception) { // Should not happen } if (COMMENT_PARTITION.equals(typeRight) || STRING_LITERAL_PARTITION.equals(typeRight) || SL_COMMENT_PARTITION.equals(typeRight) || "__rich_string".equals(typeRight)) { if (typeLeft.equals(typeRight)) return false; } return true; } private int caretOffset(final XtextEditor xtextEditor) { ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer(); int caretOffset = sourceViewer.getTextWidget().getCaretOffset(); if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; caretOffset = extension.widgetOffset2ModelOffset(caretOffset); } return caretOffset; } private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(), xbaseClipboardData.getExtensionImports(), getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(), new String[] {}, getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private boolean sameTarget(XbaseClipboardData xbaseClipboardData) { IEditorInput editorInput = getTextEditor().getEditorInput(); if (editorInput == null) { return false; } return xbaseClipboardData.getSourceIndentifier().equals(editorInput.toString()); } private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.readOnly(new IUnitOfWork() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple, Set, Set> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; } private IXtextDocument getXtextDocument() { XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); IXtextDocument document = xtextEditor.getDocument(); return document; } @Override public void update() { super.update(); if (isModifyOperation() && !canModifyEditor()) { setEnabled(false); return; } ITextEditor editor = getTextEditor(); if (textOperationTarget == null && editor != null) textOperationTarget = editor.getAdapter(ITextOperationTarget.class); boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode())); setEnabled(isEnabled); } private int getOperationCode() { return operationCode; } @Override public void run() { if (textOperationTarget == null) return; ITextEditor editor = getTextEditor(); if (editor == null) return; if (isModifyOperation() && !validateEditorInputState()) return; BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { internalDoOperation(); } }); } private boolean isModifyOperation() { return operationCode != ITextOperationTarget.COPY; } private Shell getShell() { ITextEditor editor = getTextEditor(); if (editor != null) { IWorkbenchPartSite site = editor.getSite(); Shell shell = site.getShell(); if (shell != null && !shell.isDisposed()) { return shell; } } return null; } private Display getDisplay() { Shell shell = getShell(); if (shell != null) { return shell.getDisplay(); } return null; } @Override public void setEditor(ITextEditor editor) { super.setEditor(editor); this.textOperationTarget = null; } public static final class XbaseClipboardData { private String sourceIndentifier; private String[] imports; private String[] staticImports; private String[] extensionImports; public XbaseClipboardData(String sourceIndentifier, String[] imports, String[] staticImports, String[] extensionImports) { this.sourceIndentifier = sourceIndentifier; this.imports = imports; this.staticImports = staticImports; this.extensionImports = extensionImports; } public XbaseClipboardData(byte[] bytes) throws IOException { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes)); try { sourceIndentifier = dataIn.readUTF(); imports = readArray(dataIn); staticImports = readArray(dataIn); extensionImports = readArray(dataIn); } finally { dataIn.close(); } } protected final String[] readArray(DataInputStream dataIn) throws IOException { int count = dataIn.readInt(); String[] array = new String[count]; for (int i = 0; i < count; i++) { array[i] = dataIn.readUTF(); } return array; } public byte[] serialize() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); try { dataOut.writeUTF(sourceIndentifier); writeArray(dataOut, imports); writeArray(dataOut, staticImports); writeArray(dataOut, extensionImports); } finally { dataOut.close(); out.close(); } return out.toByteArray(); } protected final void writeArray(DataOutputStream dataOut, String[] array) throws IOException { dataOut.writeInt(array.length); for (int i = 0; i < array.length; i++) { dataOut.writeUTF(array[i]); } } public String getSourceIndentifier() { return sourceIndentifier; } public String[] getImports() { return imports; } public String[] getStaticImports() { return staticImports; } public String[] getExtensionImports() { return extensionImports; } } private static class XbaseClipboardTransfer extends ByteArrayTransfer { private static final String TYPE_NAME = "xbase-source-with-imports-transfer-format"; private static final int TYPEID = registerType(TYPE_NAME); @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object data, TransferData transferData) { if (data instanceof XbaseClipboardData) { try { super.javaToNative(((XbaseClipboardData) data).serialize(), transferData); } catch (IOException e) { //it's best to send nothing if there were problems } } } @Override protected Object nativeToJava(TransferData transferData) { byte[] bytes = (byte[]) super.nativeToJava(transferData); if (bytes != null) { try { return new XbaseClipboardData(bytes); } catch (IOException e) { } } return null; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11212 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xbase.ui/src/org/eclipse/xtext/xbase/ui/editor/actions/ImportsAwareClipboardAction.java/#L79-L520 | 1 | 1534 | 11212 | critical |
| 1566 | YES I found bad smells 1. Magic number (currently not used) 2. Unused variables (sysDir, stagingAreaDir, jobHistoryDir) 3. Long method (initialize, close, getFileSystem, getJob) 4. Feature envy (ClientProtocol, UserGroupInformation, Configuration) 5. Inappropriate static method (loadResources) 6. Empty catch block (catch (Exception e)) 7. Unused imports (@InterfaceAudience, @InterfaceStability) 8. Tightly coupled code (synchronized block in initialize method) 9. Inconsistent coding style (some methods are camelCase and some are underscore_separated) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Magic number (currently not used)2 Unused variables (sysDir, stagingAreaDir, jobHistoryDir)3 Long method (initialize, close, getFileSystem, getJob)4 Feature envy (ClientProtocol, UserGroupInformation, Configuration)5 Inappropriate static method (loadResources)6 Empty catch block (catch (Exception e))7 Unused imports (@InterfaceAudience, @InterfaceStability)8 Tightly coupled code (synchronized block in initialize method)9 Inconsistent coding style (some methods are camelCase and some are underscore_separated) | t | f | f | . Magic number (currently not used)2. Unused variables (sysDir, stagingAreaDir, jobHistoryDir)3. Long method (initialize, close, getFileSystem, getJob)4. Feature envy (ClientProtocol, UserGroupInformation, Configuration)5. Inappropriate static method (loadResources)6. Empty catch block (catch (Exception e))7. Unused imports (@InterfaceAudience, @InterfaceStability)8. Tightly coupled code (synchronized block in initialize method)9. Inconsistent coding style (some methods are camelCase and some are underscore_separated) | data class | 0 | 11327 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 1566 | 11327 | minor |
| 3855 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class MouseObservationEvent extends ObservationEvent { private int deltaX; private int deltaY; private int deltaZ; public MouseObservationEvent(int deltaX, int deltaY, int deltaZ) { super(); this.deltaX = deltaX; this.deltaY = deltaY; this.deltaZ = deltaZ; } @Override public JsonObject getJSON() { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("time", this.timestamp); jsonEvent.addProperty("type", "mouse"); jsonEvent.addProperty("deltaX", this.deltaX); jsonEvent.addProperty("deltaY", this.deltaY); jsonEvent.addProperty("deltaZ", this.deltaZ); return jsonEvent; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 10011 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/ObservationFromHumanImplementation.java/#L29-L54 | 2 | 3855 | 10011 | minor |
| 522 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static ResumptionAction fromName(String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } for (int i = 0; i < PRIVATE_VALUES.length; i++) { if (name.equals(PRIVATE_VALUES[i].name)) { return PRIVATE_VALUES[i]; } } throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 5419 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/ResumptionAction.java/#L79-L92 | 1 | 522 | 5419 | minor |
| 2215 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13529 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 2215 | 13529 | minor |
| 1766 | YES, I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11911 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 2 | 1766 | 11911 | minor |
| 2522 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
blob | Long Method"} | t | f | f | . Long Method"} | blob | 0 | 14711 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 2522 | 14711 | minor |
| 1692 | { "message": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | t | f | f | long method | 0 | 11712 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 1 | 1692 | 11712 | major | ||
| 215 | { "message": "YES, I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2326 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 2 | 215 | 2326 | major |
| 2005 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12720 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 2005 | 12720 | minor |
| 1473 | YES I found bad smells, the bad smells are: 1. Feature envy - the MultiSpinnerUI class is accessing and using methods and variables from the parent SpinnerUI class and other classes, creating a dependency and violating encapsulation. 2. Long method - the contains(), update(), installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are all long and perform multiple operations, violating the "single responsibility principle". 3. Duplicate code - the code within the installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are repeated multiple times, violating the "don't repeat yourself" principle. 4. Poor naming conventions - the variable names in the code are not descriptive and could be improved (e.g. uis, a, b, c). 5. Redundant comments - some of the comments in the code are not necessary and do not provide any useful information. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | Feature envy - the MultiSpinnerUI class is accessing and using methods and variables from the parent SpinnerUI class and other classes, creating a dependency and violating encapsulation2 Long method - the contains(), update(), installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are all long and perform multiple operations, violating the "single responsibility principle"3 Duplicate code - the code within the installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are repeated multiple times, violating the "don't repeat yourself" principle4 Poor naming conventions - the variable names in the code are not descriptive and could be improved (eg uis, a, b, c)5 Redundant comments - some of the comments in the code are not necessary and do not provide any useful information | t | f | f | . Feature envy - the MultiSpinnerUI class is accessing and using methods and variables from the parent SpinnerUI class and other classes, creating a dependency and violating encapsulation.2. Long method - the contains(), update(), installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are all long and perform multiple operations, violating the "single responsibility principle".3. Duplicate code - the code within the installUI(), uninstallUI(), paint(), getPreferredSize(), getMinimumSize(), getMaximumSize(), getAccessibleChildrenCount(), and getAccessibleChild() methods are repeated multiple times, violating the "don't repeat yourself" principle.4. Poor naming conventions - the variable names in the code are not descriptive and could be improved (e.g. uis, a, b, c).5. Redundant comments - some of the comments in the code are not necessary and do not provide any useful information. | blob | 0 | 11053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 2 | 1473 | 11053 | minor |
| 2189 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "The 'Statement' class contains multiple methods that can be considered long." } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | 1. long method: the statement class contains multiple methods that can be considered long. | t | t | f | 1. long method: the statement class contains multiple methods that can be considered long. | data class | 0 | 13450 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 1 | 2189 | 13450 | minor |
| 2471 | YES I found bad smells The bad smells are: 1. Empty constructor, 2. Insufficient encapsulation, 3. Boolean as a method name. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Empty constructor, 2 Insufficient encapsulation, 3 Boolean as a method name | t | f | f | . Empty constructor, 2. Insufficient encapsulation, 3. Boolean as a method name. | data class | 0 | 14578 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 2471 | 14578 | major |
| 2247 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13660 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 2 | 2247 | 13660 | minor |
| 1879 | YES I found bad smells the bad smells are: 1. Deprecated class 2. Deprecated methods 3. Long method 4. Feature envy 5. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; } |
blob | Deprecated class2 Deprecated methods3 Long method4 Feature envy5 Lack of comments/documentation | t | f | f | . Deprecated class2. Deprecated methods3. Long method4. Feature envy5. Lack of comments/documentation | blob | 0 | 12276 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 | 2 | 1879 | 12276 | critical |
| 487 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 4794 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 2 | 487 | 4794 | minor |
| 1174 | YES I found bad smells 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 10210 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 1174 | 10210 | critical |
| 800 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7573 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 2 | 800 | 7573 | minor |
| 1267 | YES I found bad smells the bad smells are: 1. Feature envy: getUIs() method is accessing elements from the uis Vector, which it does not belong to and has no access to. 2. Long method: contains() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 3. Long method: update() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 4. Long method: installUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 5. Long method: uninstallUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 6. Long method: paint() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 7. Long method: getPreferredSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 8. Long method: getMinimumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 9. Long method: getMaximumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 10. Long method: getAccessibleChildrenCount() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. 11. Long method: getAccessibleChild() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | Feature envy: getUIs() method is accessing elements from the uis Vector, which it does not belong to and has no access to2 Long method: contains() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods3 Long method: update() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods4 Long method: installUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods5 Long method: uninstallUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods6 Long method: paint() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods7 Long method: getPreferredSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods8 Long method: getMinimumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods9 Long method: getMaximumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods | t | f | f | . Feature envy: getUIs() method is accessing elements from the uis Vector, which it does not belong to and has no access to.2. Long method: contains() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.3. Long method: update() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.4. Long method: installUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.5. Long method: uninstallUI() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.6. Long method: paint() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.7. Long method: getPreferredSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.8. Long method: getMinimumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods.9. Long method: getMaximumSize() method contains a for loop that iterates through all elements in the uis Vector, which could be separated into smaller, more specific methods. | blob | 0 | 10549 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 2 | 1267 | 10549 | minor |
| 2039 | YES I found bad smells the bad smells are: 1.Long method, 2.Long class, 3.Improper exception handling, 4.Magic numbers, 5.Unnecessary comments, 6.Inconsistent naming conventions, 7.Redundant code, 8.Feature envy, 9.Data class, 10.Inappropriate identifiers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | Long method, 2Long class, 3Improper exception handling, 4Magic numbers, 5Unnecessary comments, 6Inconsistent naming conventions, 7Redundant code, 8Feature envy, 9Data class, | t | f | f | .Long method, 2.Long class, 3.Improper exception handling, 4.Magic numbers, 5.Unnecessary comments, 6.Inconsistent naming conventions, 7.Redundant code, 8.Feature envy, 9.Data class, | blob | 0 | 12844 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2039 | 12844 | minor |
| 1203 | Yes I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10286 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 2 | 1203 | 10286 | major |
| 4092 | that I can see. This seems like pretty well written code~! | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 10781 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 4092 | 10781 | major | ||
| 221 | {"error": "YES I found bad smells", "the bad smells are": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } } |
data class | 1. Long method | f | f | f | 1, ., , L, o, n, g, , m, e, t, h, o, d | data class | 0 | 2394 | https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 | 2 | 221 | 2394 | minor |
| 430 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4277 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 430 | 4277 | critical |
| 1525 | YES I found bad smells The bad smells are: Long method, Feature envy, Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | Long method, Feature envy, Shotgun surgery | t | f | f | Long method, Feature envy, Shotgun surgery | blob | 0 | 11184 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 2 | 1525 | 11184 | major |
| 1642 | YES, I found bad smells: 1. Redundant variable "cGroup" and "cNameAssignment_0" 2. Redundant variable "cGroup_1" and "cTypeAssignment_1_1" 3. Redundant variable "cColonKeyword_1_0" 4. Redundant method "getRule()" 5. Redundant method "getGroup()" 6. Redundant method "getNameAssignment_0()" 7. Redundant method "getNameIdentifierParserRuleCall_0_0()" 8. Redundant method "getGroup_1()" 9. Redundant method "getColonKeyword_1_0()" 10. Redundant method "getTypeAssignment_1_1()" 11. Redundant method "getTypeTypeExpParserRuleCall_1_1_0()" 12. Possible feature envy with "getGrammar()" 13. Long method with multiple assignments and inefficient code structure. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Redundant variable "cGroup" and "cNameAssignment_0"2 Redundant variable "cGroup_ | t | f | f | . Redundant variable "cGroup" and "cNameAssignment_0"2. Redundant variable "cGroup_ | data class | 0 | 11545 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 1642 | 11545 | minor |
| 2392 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
blob | long method | t | t | f | long method | blob | 0 | 14363 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 1 | 2392 | 14363 | minor |
| 2677 | YES I found bad smells 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Poor exception handling, 6. Inconsistent formatting/style, 7. Poor naming conventions, 8. Too many parameters in methods/constructors, 9. Unnecessary complexity, 10. Violation of Single Responsibility Principle. The bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Poor exception handling, 6. Inconsistent formatting/style, 7. Poor naming conventions, 8. Too many parameters in methods/constructors, 9. Unnecessary complexity, 10. Violation of Single Responsibility Principle. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Poor exception handling, 6 Inconsistent formatting/style, 7 Poor naming conventions, 8 Too many parameters in methods/constructors, 9 Unnecessary complexity, | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Poor exception handling, 6. Inconsistent formatting/style, 7. Poor naming conventions, 8. Too many parameters in methods/constructors, 9. Unnecessary complexity, | blob | 0 | 15243 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 2 | 2677 | 15243 | minor |
| 2004 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12718 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 2 | 2004 | 12718 | major |
| 33 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | long method | t | t | f | long method | data class | 0 | 732 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 33 | 732 | major |
| 2365 | YES, I found bad smells. The bad smells are: 1.Long method, 2.Feature envy, 3.Inappropriate intimacy, 4.Magic numbers, 5.Message chains, 6.Long parameter list, 7.Data clump, 8.Switch statements, 9.Data class, 10.Long class, 11.Incomplete library class, 12.Multiple return statements, 13.Lazy class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | Long method, 2Feature envy, 3Inappropriate intimacy, 4Magic numbers, 5Message chains, 6Long parameter list, 7Data clump, 8Switch statements, 9Data class, | t | f | f | .Long method, 2.Feature envy, 3.Inappropriate intimacy, 4.Magic numbers, 5.Message chains, 6.Long parameter list, 7.Data clump, 8.Switch statements, 9.Data class, | blob | 0 | 14259 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 2365 | 14259 | minor |
| 140 | {"response": "YES I found bad smells the bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1770 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 140 | 1770 | major |
| 1150 | YES I found bad smells the bad smells are: 1. Long interface containing 25 methods and 11 constants. 2. Feature envy between MetricsIndexerSource and BaseSource. 3. Duplicate code in method names and descriptions related to different operations. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | Long interface containing 25 methods and | t | f | f | . Long interface containing 25 methods and | data class | 0 | 10131 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 1150 | 10131 | major |
| 296 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3115 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 2 | 296 | 3115 | major |
| 1151 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10132 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 1151 | 10132 | major |
| 586 | { "response": "YES I found bad smells", "bad smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 5819 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/protocol/src/main/java/org/apache/drill/exec/proto/UserProtos.java/#L19445-L20118 | 1 | 586 | 5819 | major |
| 2183 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | blob | t | t | f | blob | data class | 0 | 13424 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 1 | 2183 | 13424 | minor |
| 1354 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10763 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 2 | 1354 | 10763 | minor |
| 2663 | YES I found bad smells the bad smells are: 1. Long method 2. Long class 3. Magic number 4. Duplicate code 5. Complex code 6. Comments for explain - an indication of code smells 7. Feature envy 8. Dead code (unused variables and imports) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | Long method2 Long class3 Magic number 4 Duplicate code5 Complex code 6 Comments for explain - an indication of code smells7 Feature envy8 Dead code (unused variables and imports) | t | f | f | . Long method2. Long class3. Magic number 4. Duplicate code5. Complex code 6. Comments for explain - an indication of code smells7. Feature envy8. Dead code (unused variables and imports) | blob | 0 | 15198 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2663 | 15198 | minor |
| 624 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static org.apache.phoenix.coprocessor.generated.MetaDataProtos.CreateFunctionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6250 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L8189-L8194 | 1 | 624 | 6250 | minor |
| 4211 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11086 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 4211 | 11086 | major |
| 58 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue abstract class UOfKind extends UExpression { public static UOfKind create(UExpression expression, Set allowed) { return new AutoValue_UOfKind(expression, allowed); } abstract UExpression expression(); abstract Set allowed(); @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { return expression().inline(inliner); } @Override public R accept(TreeVisitor visitor, D data) { return expression().accept(visitor, data); } @Override public Kind getKind() { return expression().getKind(); } @Override @Nullable protected Choice defaultAction(Tree tree, @Nullable Unifier unifier) { return Choice.condition(allowed().contains(tree.getKind()), unifier) .thenChoose(unifications(expression(), tree)); } } |
data class | long method, blob | t | t | f | long method, blob | data class | 0 | 988 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UOfKind.java/#L33-L64 | 1 | 58 | 988 | minor |
| 5395 | { "answer": "YES I found bad smells", "detected_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 15164 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 5395 | 15164 | minor |
| 4219 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11111 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 4219 | 11111 | major |
| 1021 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9351 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 2 | 1021 | 9351 | critical |
| 191 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Long parameter list" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | long method, long parameter list | t | t | f | long method, long parameter list | blob | 0 | 2197 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 2 | 191 | 2197 | major |
| 2525 | YES I found bad smellsThe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14720 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 2525 | 14720 | minor |
| 2228 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13581 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 2228 | 13581 | major |
| 2238 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13615 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 2238 | 13615 | minor |
| 668 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
blob | Long method2Feature envy | t | f | f | .Long method2.Feature envy | blob | 0 | 6550 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 2 | 668 | 6550 | minor |
| 1852 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
blob | long method | t | t | f | long method | blob | 0 | 12191 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 1852 | 12191 | minor |
| 1871 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12249 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 1871 | 12249 | minor |
| 2157 | { "output": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | feature envy | t | t | f | feature envy | long method | 0 | 13311 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 2157 | 13311 | major |
| 2183 | YES I found bad smells, Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | t | f | f | data class | 0 | 13424 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 2 | 2183 | 13424 | minor | ||
| 1181 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10234 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 2 | 1181 | 10234 | critical |
| 716 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6822 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 716 | 6822 | minor |
| 415 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4221 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 2 | 415 | 4221 | major |
| 4074 | YES I found bad smells the bad smells are: 1. Long method, 2. Inconsistent naming (e.g. testST and sequenceType), 3. Coupled logic (each if statement depends on the previous one), 4. Opaque and confusing logic (e.g. the variable vType), 5. Duplicate code (check for AtomicType and NodeType is similar), 6. Inefficient use of inheritance (using instanceof instead of polymorphism), 7. Inconsistent formatting (indentation is inconsistent), 8. Over-complicated logic (multiple nested if statements), 9. Magic numbers (e.g. NodeKind constants), 10. No comments or documentation to explain the purpose of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
feature envy | Long method, 2 Inconsistent naming (eg testST and sequenceType), 3 Coupled logic (each if statement depends on the previous one), 4 Opaque and confusing logic (eg the variable vType), 5 Duplicate code (check for AtomicType and NodeType is similar), 6 Inefficient use of inheritance (using instanceof instead of polymorphism), 7 Inconsistent formatting (indentation is inconsistent), 8 Over-complicated logic (multiple nested if statements), 9 Magic numbers (eg NodeKind constants), | t | f | f | . Long method, 2. Inconsistent naming (e.g. testST and sequenceType), 3. Coupled logic (each if statement depends on the previous one), 4. Opaque and confusing logic (e.g. the variable vType), 5. Duplicate code (check for AtomicType and NodeType is similar), 6. Inefficient use of inheritance (using instanceof instead of polymorphism), 7. Inconsistent formatting (indentation is inconsistent), 8. Over-complicated logic (multiple nested if statements), 9. Magic numbers (e.g. NodeKind constants), | feature envy | 0 | 10748 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 4074 | 10748 | minor |
| 1099 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9827 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 2 | 1099 | 9827 | minor |
| 3854 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10010 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 3854 | 10010 | major |
| 390 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface CassandraSieveRepositoryModule { CassandraModule MODULE = CassandraModule.builder() .table(CassandraSieveTable.TABLE_NAME) .comment("Holds SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveTable.USER_NAME, text()) .addClusteringColumn(CassandraSieveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveTable.SCRIPT_CONTENT, text()) .addColumn(CassandraSieveTable.IS_ACTIVE, cboolean()) .addColumn(CassandraSieveTable.SIZE, bigint())) .table(CassandraSieveSpaceTable.TABLE_NAME) .comment("Holds per user current space occupied by SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveSpaceTable.USER_NAME, text()) .addColumn(CassandraSieveSpaceTable.SPACE_USED, counter())) .table(CassandraSieveQuotaTable.TABLE_NAME) .comment("Holds per user size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveQuotaTable.USER_NAME, text()) .addColumn(CassandraSieveQuotaTable.QUOTA, bigint())) .table(CassandraSieveClusterQuotaTable.TABLE_NAME) .comment("Holds default size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveClusterQuotaTable.NAME, text()) .addColumn(CassandraSieveClusterQuotaTable.VALUE, bigint())) .table(CassandraSieveActiveTable.TABLE_NAME) .comment("Denormalisation table. Allows per user direct active SIEVE script retrieval.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveActiveTable.USER_NAME, text()) .addColumn(CassandraSieveActiveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveActiveTable.DATE, timestamp())) .build(); } |
blob | long method | t | t | f | long method | blob | 0 | 3954 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-cassandra/src/main/java/org/apache/james/sieve/cassandra/CassandraSieveRepositoryModule.java/#L35-L74 | 1 | 390 | 3954 | major |
| 2445 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14492 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 2445 | 14492 | critical |
| 553 | YES I found bad smells the bad smells are: 1. Deprecated annotation used multiple times. 2. Long method (the method "CompactCharArray()" contains a high number of lines). 3. Long method (the method "CompactCharArray(String, String)" contains a high number of lines). 4. Feature envy (the method "elementAt(char)" accesses fields from CompactCharArray object instead of using local variables). 5. Feature envy (the method "getElementArray()" accesses fields from CompactCharArray object instead of using local variables). 6. Magic numbers (usage of hardcoded numbers instead of named constants in conditions such as "BLOCKCOUNT" or "INDEXSHIFT"). 7. Unused variables (the variable "defaultValue" is declared but never used). 8. Inconsistent code formatting and style (indentation, spacing, and brackets placement varies throughout the code). 9. Redundant comments (some comments do not provide additional information and can be removed). 10. Lack of proper documentation for some methods (e.g. "expand()" has no explanation of its purpose or functionality). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; } |
blob | Deprecated annotation used multiple times 2 Long method (the method "CompactCharArray()" contains a high number of lines) 3 Long method (the method "CompactCharArray(String, String)" contains a high number of lines) 4 Feature envy (the method "elementAt(char)" accesses fields from CompactCharArray object instead of using local variables) 5 Feature envy (the method "getElementArray()" accesses fields from CompactCharArray object instead of using local variables) 6 Magic numbers (usage of hardcoded numbers instead of named constants in conditions such as "BLOCKCOUNT" or "INDEXSHIFT") 7 Unused variables (the variable "defaultValue" is declared but never used) 8 Inconsistent code formatting and style (indentation, spacing, and brackets placement varies throughout the code) 9 Redundant comments (some comments do not provide additional information and can be removed) | t | f | f | . Deprecated annotation used multiple times. 2. Long method (the method "CompactCharArray()" contains a high number of lines). 3. Long method (the method "CompactCharArray(String, String)" contains a high number of lines). 4. Feature envy (the method "elementAt(char)" accesses fields from CompactCharArray object instead of using local variables). 5. Feature envy (the method "getElementArray()" accesses fields from CompactCharArray object instead of using local variables). 6. Magic numbers (usage of hardcoded numbers instead of named constants in conditions such as "BLOCKCOUNT" or "INDEXSHIFT"). 7. Unused variables (the variable "defaultValue" is declared but never used). 8. Inconsistent code formatting and style (indentation, spacing, and brackets placement varies throughout the code). 9. Redundant comments (some comments do not provide additional information and can be removed). | blob | 0 | 5576 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 | 2 | 553 | 5576 | minor |
| 373 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Service ("knownRepositoryContentConsumer#create-archiva-metadata") @Scope ("prototype") public class ArchivaMetadataCreationConsumer extends AbstractMonitoredConsumer implements KnownRepositoryContentConsumer, RegistryListener { private String id = "create-archiva-metadata"; private String description = "Create basic metadata for Archiva to be able to reference the artifact"; @Inject private ArchivaConfiguration configuration; @Inject private FileTypes filetypes; private Date whenGathered; private List includes = new ArrayList<>( 0 ); /** * FIXME: this could be multiple implementations and needs to be configured. */ @Inject private RepositorySessionFactory repositorySessionFactory; /** * FIXME: this needs to be configurable based on storage type - and could also be instantiated per repo. Change to a * factory. */ @Inject @Named (value = "repositoryStorage#maven2") private RepositoryStorage repositoryStorage; private static final Logger log = LoggerFactory.getLogger( ArchivaMetadataCreationConsumer.class ); private String repoId; @Override public String getId() { return this.id; } @Override public String getDescription() { return this.description; } @Override public List getExcludes() { return getDefaultArtifactExclusions(); } @Override public List getIncludes() { return this.includes; } @Override public void beginScan( ManagedRepository repo, Date whenGathered ) throws ConsumerException { repoId = repo.getId(); this.whenGathered = whenGathered; } @Override public void beginScan( ManagedRepository repository, Date whenGathered, boolean executeOnEntireRepo ) throws ConsumerException { beginScan( repository, whenGathered ); } @Override public void processFile( String path ) throws ConsumerException { RepositorySession repositorySession = repositorySessionFactory.createSession(); try { // note that we do minimal processing including checksums and POM information for performance of // the initial scan. Any request for this information will be intercepted and populated on-demand // or picked up by subsequent scans ArtifactMetadata artifact = repositoryStorage.readArtifactMetadataFromPath( repoId, path ); ProjectMetadata project = new ProjectMetadata(); project.setNamespace( artifact.getNamespace() ); project.setId( artifact.getProject() ); String projectVersion = VersionUtil.getBaseVersion( artifact.getVersion() ); MetadataRepository metadataRepository = repositorySession.getRepository(); boolean createVersionMetadata = false; // FIXME: maybe not too efficient since it may have already been read and stored for this artifact ProjectVersionMetadata versionMetadata = null; try { ReadMetadataRequest readMetadataRequest = new ReadMetadataRequest().repositoryId( repoId ).namespace( artifact.getNamespace() ).projectId( artifact.getProject() ).projectVersion( projectVersion ); versionMetadata = repositoryStorage.readProjectVersionMetadata( readMetadataRequest ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataNotFoundException e ) { log.warn( "Missing or invalid POM for artifact:{} (repository:{}); creating empty metadata", path, repoId ); versionMetadata = new ProjectVersionMetadata(); versionMetadata.setId( projectVersion ); versionMetadata.setIncomplete( true ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataInvalidException e ) { log.warn( "Error occurred resolving POM for artifact:{} (repository:{}); message: {}", new Object[]{ path, repoId, e.getMessage() } ); } // read the metadata and update it if it is newer or doesn't exist artifact.setWhenGathered( whenGathered ); metadataRepository.updateArtifact( repoId, project.getNamespace(), project.getId(), projectVersion, artifact ); if ( createVersionMetadata ) { metadataRepository.updateProjectVersion( repoId, project.getNamespace(), project.getId(), versionMetadata ); } metadataRepository.updateProject( repoId, project ); repositorySession.save(); } catch ( MetadataRepositoryException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}" , path, repoId, e.getMessage(), e ); repositorySession.revert(); } catch ( RepositoryStorageRuntimeException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}", path, repoId, e.getMessage(), e ); repositorySession.revert(); } finally { repositorySession.close(); } } @Override public void processFile( String path, boolean executeOnEntireRepo ) throws ConsumerException { processFile( path ); } @Override public void completeScan() { /* do nothing */ } @Override public void completeScan( boolean executeOnEntireRepo ) { completeScan(); } @Override public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { if ( ConfigurationNames.isRepositoryScanning( propertyName ) ) { initIncludes(); } } @Override public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { /* do nothing */ } private void initIncludes() { includes = new ArrayList( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) ); } @PostConstruct public void initialize() { configuration.addChangeListener( this ); initIncludes(); } } |
blob | long method | t | t | f | long method | blob | 0 | 3862 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-consumers/archiva-metadata-consumer/src/main/java/org/apache/archiva/consumers/metadata/ArchivaMetadataCreationConsumer.java/#L59-L264 | 1 | 373 | 3862 | minor |
| 210 | {"response": "YES, I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 210 | 2313 | major |
| 205 | { "response": "YES I found bad smells.", "the bad smells are": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2299 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 2 | 205 | 2299 | minor |
| 1786 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 11979 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 1786 | 11979 | minor |
| 8 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
blob | long method | t | t | f | long method | blob | 0 | 592 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 1 | 8 | 592 | major |
| 4412 | return 1. None YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | NoneYES I found bad smellsThe bad smells are: | t | f | f | . NoneYES I found bad smellsThe bad smells are: | feature envy | 0 | 11683 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 4412 | 11683 | minor |
| 1973 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12612 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 1 | 1973 | 12612 | minor | ||
| 2085 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | long method | t | t | f | long method | blob | 0 | 13099 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 2085 | 13099 | minor |
| 1223 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy 3. Lack of encapsulation/ data hiding | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | Long methods2 Feature envy3 Lack of encapsulation/ data hiding | t | f | f | . Long methods2. Feature envy3. Lack of encapsulation/ data hiding | data class | 0 | 10340 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 2 | 1223 | 10340 | critical |
| 2269 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13750 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 1 | 2269 | 13750 | major |
| 1022 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9352 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1022 | 9352 | major |
| 1153 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 10135 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 2 | 1153 | 10135 | major |
| 1748 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11856 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 1748 | 11856 | major |
| 1369 | YES I found bad smells the bad smells are: 1) Long method, 2) Feature envy, 3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | ) Long method, 2) Feature envy,3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter | t | f | f | ) Long method, 2) Feature envy, 3) Duplicate code, 4) Poor naming conventions, 5) Use of raw types rather than generic types, 6) Inappropriate abstraction, 7) Use of static state on classes, 8) Use of nested classes for every event emitter. | data class | 0 | 10791 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 1369 | 10791 | minor |
| 1572 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Feature Envy | t | f | f | Feature Envy | long method | 0 | 11341 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 1572 | 11341 | minor |
| 2173 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13386 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 2173 | 13386 | minor |
| 1100 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void processRTTmeasurement(long measuredRTT, Exchange exchange, int retransmissionCount){ //System.out.println("Measured an RTT of " + measuredRTT + " after using " + retransmissionCount + " retries." ); RemoteEndpoint endpoint = getRemoteEndpoint(exchange); int rtoType = endpoint.getExchangeEstimatorState(exchange); // The basic rto algorithm does not care for the blind estimator, set weak/strong to false endpoint.setBlindStrong(false); endpoint.setBlindWeak(false); //Perform normal update of the RTO updateEstimator(measuredRTT, rtoType, endpoint); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9830 | https://github.com/eclipse/californium/blob/0dd6db579be90c514dd765027ec55ed7a4668337/californium-core/src/main/java/org/eclipse/californium/core/network/stack/congestioncontrol/BasicRto.java/#L40-L52 | 2 | 1100 | 9830 | minor |
| 1996 | {"response": "YES, I found bad smells", "the bad smells are":["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Cel4rreg { long seghigh; long seglow; int p_dsafmt = -1; long p_dsaptr; RegisterSet regs; /** * Creates the instance and attempts to locate the registers. */ Cel4rreg() { /* Debug option - before we do anything else, try using the old svcdump code */ String useSvcdump = System.getProperty("zebedee.use.svcdump"); if (useSvcdump != null && useSvcdump.equals("true")) { getRegistersFromSvcdump(); return; } /* * Try and get the registers from the following locations: * * 1) RTM2 work area * 2) BPXGMSTA service * 3) linkage stack entries * 4) TCB * 5) Usta * * if any succeeds we return otherwise move to the next location. */ int whereCount = 0; try { if ((regs = getRegistersFromRTM2()) != null && whereCount++ >= whereSkip) { whereFound = "RTM2"; failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } /* If we still have not found a dsa, invoke kernel svs */ try { if ((regs = getRegistersFromBPXGMSTA()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (whereFound == null) whereFound = "BPXGMSTA"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { //throw new Error("oops: " + e); } try { if ((regs = getRegistersFromLinkageStack()) != null && whereCount++ >= whereSkip) { whereFound = "Linkage"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "Cel4rreg","Unexepected exception", e); throw new Error("Unexpected IOException: " + e); } try { if ((regs = getRegistersFromTCB()) != null && whereCount++ >= whereSkip) { whereFound = "TCB"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } try { if (is64bit) { /* This is from celqrreg.plx370: "Get the save R4 from a NOSTACK call" */ long lca = CeexlaaTemplate.getCeelaa_lca64(inputStream, laa); p_dsaptr = CeelcaTemplate.getCeelca_savstack(inputStream, lca); log.fine("p_dsaptr from lca = " + hex(p_dsaptr)); p_dsafmt = stackdirection = CEECAASTACK_DOWN; if (validateDSA() == 0 && whereCount++ >= whereSkip) { whereFound = "LCA"; return; } } } catch (IOException e) { throw new Error("oops: " + e); } /* Last ditch */ try { if ((regs = getRegistersFromUsta()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { } whereFound = "not found"; } /** * Try and get the registers from the RTM2 work area. Returns null if none found. As a * side-effect it also sets the stackdirection. */ private RegisterSet getRegistersFromRTM2() throws IOException { int level = ceecaalevel(); log.finer("caa level is " + level); /* If the CAA level is 13 or greater, get stack direction from * CAA. For older releases or the dummy CAA, default stack * direction to UP. */ if (is64bit) { /* Always use downstack in 64-bit mode? */ stackdirection = CEECAASTACK_DOWN; log.finer("stack direction is down"); } else if (level >= 13) { /* If LE 2.10 or higher */ /* Obtain dsa format from the CAA */ stackdirection = ceecaa_stackdirection(); log.finer("stack direction is " + (stackdirection == CEECAASTACK_UP ? "up" : "down")); } else { stackdirection = CEECAASTACK_UP; log.finer("stack direction is up"); } if ((stackdirection == CEECAASTACK_DOWN) && !is64bit) { try { long tempptr = ceecaasmcb(); //the ceecaasmcb call is not currently supported for 64 bit CAAs seghigh = SmcbTemplate.getSmcb_dsbos(inputStream, tempptr); seglow = CeexstkhTemplate.getStkh_stackfloor(inputStream, seghigh); } catch (Exception e) { //throw new Error("oops: " + e); return null; } } /* At this point, a valid CAA has been obtained. Access the RTM2 to obtain the DSA. */ long rtm2ptr = tcb.tcbrtwa(); if (rtm2ptr != 0) { try { log.finer("found some rtm2 registers"); RegisterSet regs = new RegisterSet(); long rtm2grs = rtm2ptr + Ihartm2aTemplate.getRtm2ereg$offset(); long rtm2grshi = rtm2ptr + Ihartm2aTemplate.getRtm2g64h$offset(); for (int i = 0; i < 16; i++) { long low = space.readUnsignedInt(rtm2grs + i*4); long high = is64bit ? space.readUnsignedInt(rtm2grshi + i*4) : 0; regs.setRegister(i, (high << 32) | low); } long rtm2psw = rtm2ptr + Ihartm2aTemplate.getRtm2apsw$offset(); regs.setPSW(space.readLong(rtm2psw)); if (registersValid(regs)) { log.finer("found good dsa in rtm2"); } else { log.finer("bad dsa in rtm2"); regs = null; } return regs; } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } } else { log.finer("failed to get registers from rtm2"); return null; } } /** * Validates the given register set with retry for down stack */ private boolean registersValid(RegisterSet regs) throws IOException { if (regs == null) return false; p_dsafmt = stackdirection; if (p_dsafmt == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } int lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } else { if (stackdirection == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 (again) = " + hex(p_dsaptr)); p_dsafmt = CEECAASTACK_UP; lastrc = validateDSA(); if (lastrc == WARNING) { lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } } } /* reset values */ log.finer("p_dsaptr invalid so reset: " + hex(p_dsaptr)); p_dsaptr = 0; } return false; } /** * Try and get the registers from the BPXGMSTA service. */ private RegisterSet getRegistersFromBPXGMSTA() throws IOException { RegisterSet regs = tcb.getRegistersFromBPXGMSTA(); if (is64bit) // celqrreg appears to always assume down stack stackdirection = CEECAASTACK_DOWN; if (registersValid(regs)) { log.finer("found good dsa in BPXGMSTA"); return regs; } else { log.finer("BPX registers are invalid so keep looking"); return null; } } /** * Try and get the registers from the linkage stack. */ private RegisterSet getRegistersFromLinkageStack() throws IOException { log.finer("enter getRegistersFromLinkageStack"); try { Lse[] linkageStack = tcb.getLinkageStack(); /* If Linkage stack is empty, leave */ if (linkageStack.length == 0) { log.finer("empty linkage stack"); return null; } for (int i = 0; i < linkageStack.length; i++) { Lse lse = linkageStack[i]; if (lse.lses1pasn() == space.getAsid()) { RegisterSet regs = new RegisterSet(); if (lse.isZArchitecture() && (lse.lses1typ7() == Lse.LSED1PC || lse.lses1typ7() == Lse.LSED1BAKR)) { log.finer("found some z arch registers"); regs.setPSW(lse.lses1pswh()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lses1grs(j)); } } else { log.finer("found some non z arch registers"); regs.setPSW(lse.lsespsw()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lsesgrs(j)); } } if (registersValid(regs)) { log.finer("found good dsa in linkage stack"); return regs; } } else { log.finer("different asid: " + hex(lse.lses1pasn())); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } log.finer("could not find registers in linkage stack"); return null; } /** * Try and get the registers from the TCB. */ private RegisterSet getRegistersFromTCB() throws IOException { log.finer("getRegistersFromTCB"); RegisterSet regs = tcb.getRegisters(); if (registersValid(regs)) { log.finer("found good dsa in TCB"); return regs; } else { return null; } } /** * Try and get the registers from the Usta. Note that this is a kind of last-ditch * thing and so no validation is done. */ private RegisterSet getRegistersFromUsta() throws IOException { log.fine("enter getRegistersFromUsta"); RegisterSet regs = tcb.getRegistersFromUsta(); if (registersValid(regs)) { log.finer("found good dsa in Usta"); return regs; } else { /* If there are more than three stack entries that's probably better than nothing */ boolean isDownStack = stackdirection == CEECAASTACK_DOWN; long dsaptr; if (isDownStack) { dsaptr = regs.getRegister(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { dsaptr = regs.getRegister(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } try { DsaStackFrame dsa = new DsaStackFrame(dsaptr, isDownStack, regs, space, Caa.this); int count = 0; for (; dsa != null; dsa = dsa.getParentFrame()) { if (++count > 3) { p_dsaptr = dsaptr; p_dsafmt = stackdirection; return regs; } } } catch (IOException e) { } catch (AssertionError e) { } } return null; } /** * Try and get the registers using the old svcdump code. This is for debugging * purposes only. Uses reflection so there is no compilation dependency. */ private void getRegistersFromSvcdump() { } /** * Validate the given DSA. Returns 0 if valid. Note because this is Java, we can't * modify the input parameters, so we use the instance variables instead and * val_dsa == p_dsaptr, val_dsafmt == p_dsafmt. */ private int validateDSA() { log.finer("attempt to validate " + hex(p_dsaptr) + " on " + (p_dsafmt == CEECAASTACK_DOWN ? "down" : "up") + " stack"); try { if (is64bit) { assert laa != 0; long l_sancptr = CeexlaaTemplate.getCeelaa_sanc64(inputStream, laa); assert l_sancptr != 0; long seghigh = CeexsancTemplate.getSanc_bos(inputStream, l_sancptr); long seglow = 0; long sanc_stack = CeexsancTemplate.getSanc_stack(inputStream, l_sancptr); long sanc_user_stack = CeexsancTemplate.getSanc_user_stack(inputStream, l_sancptr); if (sanc_stack == sanc_user_stack) { /* Get Stackfloor from sanc */ seglow = CeexsancTemplate.getSanc_user_floor(inputStream, l_sancptr); } else { /* Get StackFloor from LAA */ seglow = CeexlaaTemplate.getCeelaa_stackfloor64(inputStream, laa); } if (p_dsaptr < seghigh && (p_dsaptr + 0x800) >= seglow && (p_dsaptr & 0xf) == 0) { log.finer("dsa " + hex(p_dsaptr) + " is within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return 0; } else { log.finer("dsa " + hex(p_dsaptr) + " is NOT within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return ERROR; } } if (p_dsafmt == CEECAASTACK_DOWN) { /* the check for being in the current segment is commented out */ } else { if (is64bit) return ERROR; long tptr = ceecaaerrcm(); /* Chicken egg situation */ //assert !space.is64bit(); /* If the input DSA address is within the HCOM and double word aligned, * assume that it is good. */ if (p_dsaptr < (tptr + hcomLength) && p_dsaptr >= tptr && (p_dsaptr & 7) == 0) { log.finer("upstack dsa " + hex(p_dsaptr) + " is inside hcom"); return 0; } } long ddsa = ceecaaddsa(); long dsaptr = p_dsaptr; int dsafmt8 = p_dsafmt; long slowdsaptr = p_dsaptr; int slowdsafmt8 = p_dsafmt; for (boolean slow = false;; slow = !slow) { Ceexdsaf dsaf = new Ceexdsaf(space, dsaptr, dsafmt8, is64bit); /* If the stack direction is down but we are validating an upstack DSA * and the current DSA is inside the current segment of the down stack, * assume this must be a OS_NOSTACK call, return WARNING and replace * input DSA and DSAFmt with R4 value from this DSA */ log.finer("looping with dsa = " + hex(dsaptr)); if (stackdirection == CEECAASTACK_DOWN && p_dsafmt == CEECAASTACK_UP && dsaptr < seghigh && dsaptr >= seglow) { p_dsaptr = CeedsaTemplate.getCeedsar4(inputStream, dsaptr); p_dsafmt = CEECAASTACK_DOWN; log.finer("warning, try switching to down stack"); return WARNING; } long callers_dsaptr = dsaf.DSA_Prev; dsafmt8 = dsaf.DSA_Format; /* If we are not able to backchain any farther or we have encountered * a linkage stack, assume that the input DSA address is bad. */ if (callers_dsaptr == 0 || callers_dsaptr == F1SA) { log.finer("cannot backchain futher because " + (callers_dsaptr == 0 ? "zero" : "linkage stack") + " found"); return ERROR; } /* If we were able to backchain to the dummy DSA, the input DSA address * must be good. */ if (callers_dsaptr == ddsa) { log.finer("dummy dsa reached"); return 0; } /* If we backchained across a stack transition, assume that the input * DSA address is good. */ if (dsafmt8 != p_dsafmt) { log.finer("backchained across a stack transition"); return 0; } /* If we have located an upstack DSA with a valid NAB value, assume that * the input DSA address is good. */ if (dsafmt8 == CEECAASTACK_UP) { long tptr = CeedsaTemplate.getCeedsanab(inputStream, callers_dsaptr); if (tptr == dsaptr) { log.finer("upstack DSA is good"); return 0; } } dsaptr = callers_dsaptr; /* We use the Tortoise and the Hare algorithm to detect loops. If the slow * iterator is lapped it means there is a loop. */ if (slow) { dsaf = new Ceexdsaf(space, slowdsaptr, slowdsafmt8, is64bit); slowdsaptr = dsaf.DSA_Prev; slowdsafmt8 = dsaf.DSA_Format; } if (dsaptr == slowdsaptr) { log.finer("loop detected in DSA chain"); return ERROR; } } } catch (IOException e) { /* Any bad read means the DSA was invalid */ log.logp(Level.FINER,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Bad read", e); return ERROR; } catch (Exception e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Unexepected exception", e); throw new Error("Unexpected Exception:: " + e); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12698 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/corereaders/tdump/zebedee/le/Caa.java/#L348-L800 | 2 | 1996 | 12698 | critical |
| 2282 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | long method | t | t | f | long method | data class | 0 | 13839 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 1 | 2282 | 13839 | major |
| 2542 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14785 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 2542 | 14785 | minor |
| 1104 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FunctionTagsTable extends Composite { private final FunctionEditorInput functionEditorInput; private final KeyValueSetEditingComposite tagsEditingComposite; private final KeyValueSetDataModel tagsDataModel; public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) { super(parent, SWT.NONE); this.functionEditorInput = functionEditorInput; this.setLayout(new GridLayout()); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList()); tagsEditingComposite = new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH))) .addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH))) .addKeyValidator(new LambdaTagNameValidator()) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSaveTags(); } }) .build(this, tagsDataModel); Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttonComposite.setLayout(new GridLayout(1, false)); refresh(); } public void refresh() { Map tagMap = functionEditorInput.getLambdaClient() .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); tagsDataModel.getPairSet().clear(); for (Entry entry : tagMap.entrySet()) { tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue())); } tagsEditingComposite.refresh(); } private void onSaveTags() { try { AWSLambda lambda = functionEditorInput.getLambdaClient(); Map oldTagMap = lambda .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); List tagKeysToBeRemoved = new ArrayList<>(); for (String key : oldTagMap.keySet()) { if (!tagsDataModel.getPairSet().contains(key)) { tagKeysToBeRemoved.add(key); } } Map tagMap = new HashMap<>(); for (Pair pair : tagsDataModel.getPairSet()) { tagMap.put(pair.getKey(), pair.getValue()); } if (!tagKeysToBeRemoved.isEmpty()) { lambda.untagResource(new UntagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTagKeys(tagKeysToBeRemoved)); } lambda.tagResource(new TagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTags(tagMap)); } catch (AWSLambdaException e) { LambdaPlugin.getDefault().reportException(e.getMessage(), e); } } } |
blob | data class | t | t | f | data class | blob | 0 | 9849 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.java/#L47-L123 | 1 | 1104 | 9849 | minor |
| 1315 | YES, I found bad smells the bad smells are: 1. Long method 2. Repetitive code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method2 Repetitive code | t | f | f | . Long method2. Repetitive code | data class | 0 | 10688 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 1315 | 10688 | critical |
| 386 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Deprecated annotation","3. Commented out code","4. Use of default values in annotations","5. Stringly typed code","6. Hardcoded values"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
blob | 1. long method, 2. deprecated annotation, 3. commented out code, 4. use of default values in annotations, 5. stringly typed code, 6. hardcoded values | t | t | f | 1. long method, 2. deprecated annotation, 3. commented out code, 4. use of default values in annotations, 5. stringly typed code, 6. hardcoded values | blob | 0 | 3940 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 2 | 386 | 3940 | major |
| 1519 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
feature envy | Blob, Long Method | t | f | f | Blob, Long Method | feature envy | 0 | 11171 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 1519 | 11171 | minor |
| 2038 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 12843 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 2038 | 12843 | minor |
| 1593 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Large Class 4. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
blob | Long method2 Data class3 Large Class4 Feature Envy | t | f | f | . Long method2. Data class3. Large Class4. Feature Envy | blob | 0 | 11406 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 1593 | 11406 | minor |
| 2897 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2135 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L33809-L33879 | 1 | 2897 | 2135 | minor | ||
| 1909 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 12397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 1 | 1909 | 12397 | minor |
| 3506 | , all the code is well designed. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7525 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 2 | 3506 | 7525 | minor | ||
| 397 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | f | f | f | feature envy | 0 | 4060 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 2 | 397 | 4060 | major | ||
| 2161 | YES I found bad smells The bad smells are: 1. Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose. 2. Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle. 3. Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data. 4. Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification. 5. Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base. 6. Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand. 7. Magic numbers - The code contains several hardcoded numbers, such as 0, 1, and 2, which can make the code less readable and may lead to errors if the numbers are changed in the future. 8. Similar methods - The TupleImpl class has several methods that perform similar actions, such as getString(), getInteger(), getLong(), etc. This can indicate that the class may not be well-designed and may benefit from refactoring. 9. Poor naming conventions - Some of the variable names, such as _map and _meta, do not follow standard naming conventions and may be confusing for other developers to understand. 10. Direct object manipulation - The code directly accesses and modifies object data, which can violate the principles of proper object-oriented programming. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose2 Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle3 Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data4 Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification5 Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base6 Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand7 Magic numbers - The code contains several hardcoded numbers, such as 0, | t | f | f | . Long class - The class has a lot of different methods, which can indicate that it is trying to do too many things and may not be focused on a specific purpose.2. Long parameter list - The constructor for the TupleImpl class has 5 parameters, which can be a sign that the class is trying to do too much and may be violating the Single Responsibility Principle.3. Feature envy - The TupleImpl class accesses and uses fields and methods from the GeneralTopologyContext class frequently, which can indicate that the class is more interested in the data of other classes rather than its own data.4. Too many getters and setters - The TupleImpl class has several methods for setting and getting different values, which can indicate that the class is not properly encapsulating its data and may lead to data exposure or modification.5. Comments - The code contains commented out code, which can indicate that the code is not properly maintained and increases the overall size of the code base.6. Nested classes - The code contains several nested classes within the TupleImpl class, which can make the code more complex and difficult to understand.7. Magic numbers - The code contains several hardcoded numbers, such as 0, | data class | 0 | 13324 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 2161 | 13324 | major |
| 373 | YES, I found bad smells: 1. Long method 2. Duplicate code 3. Misplaced responsibility (the class is responsible for creating metadata for Archiva, but also has injection for repository and configuration) 4. Lack of proper design (multiple FIXME comments indicate lack of proper design and potential for bugs) 5. Poor naming conventions (lack of descriptive variable names such as 'createVersionMetadata' and 'projectVersion') 6. Data clumps (multiple variables related to the repository and session) 7. Inconsistent formatting (some parts of the code are indented with spaces, while others are indented with tabs) 8. Use of magic numbers (variables such as 0 and FileTypes.ARTIFACTS should be assigned to named constants) 9. Lack of proper error handling (Exceptions are caught, but there is no clear action or message displayed) 10. Tight coupling (the class has multiple dependencies injected, which makes it tightly coupled and hard to maintain) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Service ("knownRepositoryContentConsumer#create-archiva-metadata") @Scope ("prototype") public class ArchivaMetadataCreationConsumer extends AbstractMonitoredConsumer implements KnownRepositoryContentConsumer, RegistryListener { private String id = "create-archiva-metadata"; private String description = "Create basic metadata for Archiva to be able to reference the artifact"; @Inject private ArchivaConfiguration configuration; @Inject private FileTypes filetypes; private Date whenGathered; private List includes = new ArrayList<>( 0 ); /** * FIXME: this could be multiple implementations and needs to be configured. */ @Inject private RepositorySessionFactory repositorySessionFactory; /** * FIXME: this needs to be configurable based on storage type - and could also be instantiated per repo. Change to a * factory. */ @Inject @Named (value = "repositoryStorage#maven2") private RepositoryStorage repositoryStorage; private static final Logger log = LoggerFactory.getLogger( ArchivaMetadataCreationConsumer.class ); private String repoId; @Override public String getId() { return this.id; } @Override public String getDescription() { return this.description; } @Override public List getExcludes() { return getDefaultArtifactExclusions(); } @Override public List getIncludes() { return this.includes; } @Override public void beginScan( ManagedRepository repo, Date whenGathered ) throws ConsumerException { repoId = repo.getId(); this.whenGathered = whenGathered; } @Override public void beginScan( ManagedRepository repository, Date whenGathered, boolean executeOnEntireRepo ) throws ConsumerException { beginScan( repository, whenGathered ); } @Override public void processFile( String path ) throws ConsumerException { RepositorySession repositorySession = repositorySessionFactory.createSession(); try { // note that we do minimal processing including checksums and POM information for performance of // the initial scan. Any request for this information will be intercepted and populated on-demand // or picked up by subsequent scans ArtifactMetadata artifact = repositoryStorage.readArtifactMetadataFromPath( repoId, path ); ProjectMetadata project = new ProjectMetadata(); project.setNamespace( artifact.getNamespace() ); project.setId( artifact.getProject() ); String projectVersion = VersionUtil.getBaseVersion( artifact.getVersion() ); MetadataRepository metadataRepository = repositorySession.getRepository(); boolean createVersionMetadata = false; // FIXME: maybe not too efficient since it may have already been read and stored for this artifact ProjectVersionMetadata versionMetadata = null; try { ReadMetadataRequest readMetadataRequest = new ReadMetadataRequest().repositoryId( repoId ).namespace( artifact.getNamespace() ).projectId( artifact.getProject() ).projectVersion( projectVersion ); versionMetadata = repositoryStorage.readProjectVersionMetadata( readMetadataRequest ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataNotFoundException e ) { log.warn( "Missing or invalid POM for artifact:{} (repository:{}); creating empty metadata", path, repoId ); versionMetadata = new ProjectVersionMetadata(); versionMetadata.setId( projectVersion ); versionMetadata.setIncomplete( true ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataInvalidException e ) { log.warn( "Error occurred resolving POM for artifact:{} (repository:{}); message: {}", new Object[]{ path, repoId, e.getMessage() } ); } // read the metadata and update it if it is newer or doesn't exist artifact.setWhenGathered( whenGathered ); metadataRepository.updateArtifact( repoId, project.getNamespace(), project.getId(), projectVersion, artifact ); if ( createVersionMetadata ) { metadataRepository.updateProjectVersion( repoId, project.getNamespace(), project.getId(), versionMetadata ); } metadataRepository.updateProject( repoId, project ); repositorySession.save(); } catch ( MetadataRepositoryException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}" , path, repoId, e.getMessage(), e ); repositorySession.revert(); } catch ( RepositoryStorageRuntimeException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}", path, repoId, e.getMessage(), e ); repositorySession.revert(); } finally { repositorySession.close(); } } @Override public void processFile( String path, boolean executeOnEntireRepo ) throws ConsumerException { processFile( path ); } @Override public void completeScan() { /* do nothing */ } @Override public void completeScan( boolean executeOnEntireRepo ) { completeScan(); } @Override public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { if ( ConfigurationNames.isRepositoryScanning( propertyName ) ) { initIncludes(); } } @Override public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { /* do nothing */ } private void initIncludes() { includes = new ArrayList( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) ); } @PostConstruct public void initialize() { configuration.addChangeListener( this ); initIncludes(); } } |
blob | Long method2 Duplicate code3 Misplaced responsibility (the class is responsible for creating metadata for Archiva, but also has injection for repository and configuration)4 Lack of proper design (multiple FIXME comments indicate lack of proper design and potential for bugs)5 Poor naming conventions (lack of descriptive variable names such as 'createVersionMetadata' and 'projectVersion')6 Data clumps (multiple variables related to the repository and session)7 Inconsistent formatting (some parts of the code are indented with spaces, while others are indented with tabs)8 Use of magic numbers (variables such as 0 and FileTypesARTIFACTS should be assigned to named constants)9 Lack of proper error handling (Exceptions are caught, but there is no clear action or message displayed) | t | f | f | . Long method2. Duplicate code3. Misplaced responsibility (the class is responsible for creating metadata for Archiva, but also has injection for repository and configuration)4. Lack of proper design (multiple FIXME comments indicate lack of proper design and potential for bugs)5. Poor naming conventions (lack of descriptive variable names such as 'createVersionMetadata' and 'projectVersion')6. Data clumps (multiple variables related to the repository and session)7. Inconsistent formatting (some parts of the code are indented with spaces, while others are indented with tabs)8. Use of magic numbers (variables such as 0 and FileTypes.ARTIFACTS should be assigned to named constants)9. Lack of proper error handling (Exceptions are caught, but there is no clear action or message displayed) | blob | 0 | 3862 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-consumers/archiva-metadata-consumer/src/main/java/org/apache/archiva/consumers/metadata/ArchivaMetadataCreationConsumer.java/#L59-L264 | 2 | 373 | 3862 | minor |
| 2588 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14994 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 2588 | 14994 | critical |
| 1768 | {"output": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | t | f | f | long method | 0 | 11914 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 1768 | 11914 | minor | ||
| 4206 | YES I found bad smells the bad smells are: 1. Feature envy (the get name and get id methods in the different adapter classes) 2. Long method (init method) 3. Duplicate code (creating the response in the create method in each adapter class) 4. Inappropriate coupling (the use of specific namespaces in each adapter class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
blob | Feature envy (the get name and get id methods in the different adapter classes)2 Long method (init method)3 Duplicate code (creating the response in the create method in each adapter class)4 Inappropriate coupling (the use of specific namespaces in each adapter class) | t | f | f | . Feature envy (the get name and get id methods in the different adapter classes)2. Long method (init method)3. Duplicate code (creating the response in the create method in each adapter class)4. Inappropriate coupling (the use of specific namespaces in each adapter class) | blob | 0 | 11068 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 4206 | 11068 | minor |
| 525 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
blob | data class | t | t | f | data class | blob | 0 | 5430 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 1 | 525 | 5430 | minor |
| 1393 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10847 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 2 | 1393 | 10847 | minor |
| 813 | {"response": "YES I found bad smells the bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.11.0)") public class MultiGetBuildSlaveLogDirResponse implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("MultiGetBuildSlaveLogDirResponse"); private static final org.apache.thrift.protocol.TField LOG_DIRS_FIELD_DESC = new org.apache.thrift.protocol.TField("logDirs", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new MultiGetBuildSlaveLogDirResponseStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new MultiGetBuildSlaveLogDirResponseTupleSchemeFactory(); public java.util.List logDirs; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { LOG_DIRS((short)1, "logDirs"); private static final java.util.Map byName = new java.util.HashMap(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // LOG_DIRS return LOG_DIRS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.LOG_DIRS}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.LOG_DIRS, new org.apache.thrift.meta_data.FieldMetaData("logDirs", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LogDir.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(MultiGetBuildSlaveLogDirResponse.class, metaDataMap); } public MultiGetBuildSlaveLogDirResponse() { } /** * Performs a deep copy on other. */ public MultiGetBuildSlaveLogDirResponse(MultiGetBuildSlaveLogDirResponse other) { if (other.isSetLogDirs()) { java.util.List __this__logDirs = new java.util.ArrayList(other.logDirs.size()); for (LogDir other_element : other.logDirs) { __this__logDirs.add(new LogDir(other_element)); } this.logDirs = __this__logDirs; } } public MultiGetBuildSlaveLogDirResponse deepCopy() { return new MultiGetBuildSlaveLogDirResponse(this); } @Override public void clear() { this.logDirs = null; } public int getLogDirsSize() { return (this.logDirs == null) ? 0 : this.logDirs.size(); } public java.util.Iterator getLogDirsIterator() { return (this.logDirs == null) ? null : this.logDirs.iterator(); } public void addToLogDirs(LogDir elem) { if (this.logDirs == null) { this.logDirs = new java.util.ArrayList(); } this.logDirs.add(elem); } public java.util.List getLogDirs() { return this.logDirs; } public MultiGetBuildSlaveLogDirResponse setLogDirs(java.util.List logDirs) { this.logDirs = logDirs; return this; } public void unsetLogDirs() { this.logDirs = null; } /** Returns true if field logDirs is set (has been assigned a value) and false otherwise */ public boolean isSetLogDirs() { return this.logDirs != null; } public void setLogDirsIsSet(boolean value) { if (!value) { this.logDirs = null; } } public void setFieldValue(_Fields field, java.lang.Object value) { switch (field) { case LOG_DIRS: if (value == null) { unsetLogDirs(); } else { setLogDirs((java.util.List)value); } break; } } public java.lang.Object getFieldValue(_Fields field) { switch (field) { case LOG_DIRS: return getLogDirs(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case LOG_DIRS: return isSetLogDirs(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof MultiGetBuildSlaveLogDirResponse) return this.equals((MultiGetBuildSlaveLogDirResponse)that); return false; } public boolean equals(MultiGetBuildSlaveLogDirResponse that) { if (that == null) return false; if (this == that) return true; boolean this_present_logDirs = true && this.isSetLogDirs(); boolean that_present_logDirs = true && that.isSetLogDirs(); if (this_present_logDirs || that_present_logDirs) { if (!(this_present_logDirs && that_present_logDirs)) return false; if (!this.logDirs.equals(that.logDirs)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetLogDirs()) ? 131071 : 524287); if (isSetLogDirs()) hashCode = hashCode * 8191 + logDirs.hashCode(); return hashCode; } @Override public int compareTo(MultiGetBuildSlaveLogDirResponse other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetLogDirs()).compareTo(other.isSetLogDirs()); if (lastComparison != 0) { return lastComparison; } if (isSetLogDirs()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.logDirs, other.logDirs); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("MultiGetBuildSlaveLogDirResponse("); boolean first = true; if (isSetLogDirs()) { sb.append("logDirs:"); if (this.logDirs == null) { sb.append("null"); } else { sb.append(this.logDirs); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class MultiGetBuildSlaveLogDirResponseStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public MultiGetBuildSlaveLogDirResponseStandardScheme getScheme() { return new MultiGetBuildSlaveLogDirResponseStandardScheme(); } } private static class MultiGetBuildSlaveLogDirResponseStandardScheme extends org.apache.thrift.scheme.StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // LOG_DIRS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list120 = iprot.readListBegin(); struct.logDirs = new java.util.ArrayList(_list120.size); LogDir _elem121; for (int _i122 = 0; _i122 < _list120.size; ++_i122) { _elem121 = new LogDir(); _elem121.read(iprot); struct.logDirs.add(_elem121); } iprot.readListEnd(); } struct.setLogDirsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.logDirs != null) { if (struct.isSetLogDirs()) { oprot.writeFieldBegin(LOG_DIRS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.logDirs.size())); for (LogDir _iter123 : struct.logDirs) { _iter123.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class MultiGetBuildSlaveLogDirResponseTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public MultiGetBuildSlaveLogDirResponseTupleScheme getScheme() { return new MultiGetBuildSlaveLogDirResponseTupleScheme(); } } private static class MultiGetBuildSlaveLogDirResponseTupleScheme extends org.apache.thrift.scheme.TupleScheme { @Override public void write(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetLogDirs()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetLogDirs()) { { oprot.writeI32(struct.logDirs.size()); for (LogDir _iter124 : struct.logDirs) { _iter124.write(oprot); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveLogDirResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list125 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.logDirs = new java.util.ArrayList(_list125.size); LogDir _elem126; for (int _i127 = 0; _i127 < _list125.size; ++_i127) { _elem126 = new LogDir(); _elem126.read(iprot); struct.logDirs.add(_elem126); } } struct.setLogDirsIsSet(true); } } } private static S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } } |
blob | "YES I found bad smells the bad smells are | t | f | f | "YES I found bad smells the bad smells are | blob | 0 | 7654 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/MultiGetBuildSlaveLogDirResponse.java/#L9-L423 | 1 | 813 | 7654 | major |
| 220 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2393 | https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 | 1 | 220 | 2393 | critical |
| 487 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4794 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 487 | 4794 | minor |
| 2584 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | long method, blob | t | t | f | long method, blob | data class | 0 | 14973 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 2584 | 14973 | major |
| 289 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 3068 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 2 | 289 | 3068 | major |
| 344 | {"response": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 3516 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 344 | 3516 | minor |
| 681 | {"blob": false, "data_class": false, "feature_envy": false, "long_method": true} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | Incoherent response format, very different from what was expected. | f | f | f | false | 0 | 6593 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 1 | 681 | 6593 | minor | |
| 6 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 570 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 1 | 6 | 570 | minor |
| 1244 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Comments as code 5. Magic numbers 6. Inconsistent naming conventions 7. Complex nested conditions 8. Use of static variables and methods 9. Poor exception handling 10. Use of getters and setters in the MetricsImpl class 11. Poor encapsulation 12. Violation of single responsibility principle | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | Long method2 Feature envy3 Duplicate code4 Comments as code5 Magic numbers6 Inconsistent naming conventions7 Complex nested conditions8 Use of static variables and methods9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Comments as code5. Magic numbers6. Inconsistent naming conventions7. Complex nested conditions8. Use of static variables and methods9. Poor exception handling | data class | 0 | 10416 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 1244 | 10416 | critical |
| 665 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Dead code 4. Duplicate code 5. Inconsistent formatting 6. Magic numbers/strings 7. Excessive comments 8. Mixing of responsibilities (violating single responsibility principle) 9. Inappropriate naming (variable names, method names not informative enough) 10. Poor exception handling 11. Use of deprecated methods/classes 12. Use of static variables and methods 13. Lack of error handling (NullPointerException possible) 14. Lack of proper design (use of multiple modules for a single class) 15. Code complexity (nested if/else statements) 16. Poor encapsulation (class variables not private) 17. Inadequate use of design patterns 18. Use of unchecked exceptions 19. Poor use of data structures (inefficient use of List, unnecessary conversion to Array) 20. Code duplication (in generateAsciidoc() and Stringify() methods) 21. Mixing of business logic and presentation (print statements in generateAsciidoc() method) 22. Lack of proper data validation (no check for null or empty string in prettifyDefaultValue() method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | Long method2 Feature envy3 Dead code4 Duplicate code5 Inconsistent formatting6 Magic numbers/strings7 Excessive comments8 Mixing of responsibilities (violating single responsibility principle)9 Inappropriate naming (variable names, method names not informative enough) | t | f | f | . Long method2. Feature envy3. Dead code4. Duplicate code5. Inconsistent formatting6. Magic numbers/strings7. Excessive comments8. Mixing of responsibilities (violating single responsibility principle)9. Inappropriate naming (variable names, method names not informative enough) | blob | 0 | 6531 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 2 | 665 | 6531 | minor |
| 533 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 5479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 2 | 533 | 5479 | minor |
| 97 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1279 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 97 | 1279 | major |
| 1673 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11642 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 1673 | 11642 | major |
| 1656 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 11595 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 1 | 1656 | 11595 | minor |
| 3002 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 3071 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 2 | 3002 | 3071 | major |
| 2279 | YES, I found bad smells The bad smells are: 1. Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw. 2. Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend. 3. Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code. 4. Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend. 5. Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code. 6. Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw2 Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend3 Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code4 Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend5 Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code6 Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust | t | f | f | . Feature envy - the ConfigBoolean class depends mostly on the OptionSpec class, suggesting a possible design flaw.2. Long method - the ConfigBoolean class has multiple methods that perform multiple tasks, potentially making it difficult to maintain and extend.3. Duplicate code - the set() method is duplicated with different parameters, suggesting redundancy in the code.4. Primitive obsession - the ConfigBoolean class is using primitive boolean values instead of a boolean object, potentially making it difficult to maintain and extend.5. Lack of cohesion - the addToCommandline() method does not seem to fit with the purpose of the ConfigBoolean class, suggesting a possible lack of cohesion in the code.6. Poor exception handling - the parseValue() method does not handle potential exceptions or errors that may occur when parsing the input value, making the code less robust. | data class | 0 | 13785 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 2279 | 13785 | major |
| 2109 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | f | f | f | data class | 0 | 13180 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 2109 | 13180 | minor | ||
| 1815 | YES I found bad smells The bad smells are: 1. Long methods 2. Repeated code/inconsistent naming conventions 3. Feature envy: The RemoteWasbDelegationTokenManager class has access to private variables and methods (such as makeRemoteRequest()) from the WasbRemoteCallHelper class, indicating that it may be too dependent on this external class. 4. Duplicate code: The code for handling different operations (GETDELEGATIONTOKEN, RENEWDELEGATIONTOKEN, CANCELDELEGATIONTOKEN) is repeated in the getDelegationToken(), renewDelegationToken(), and cancelDelegationToken() methods. 5. Magic numbers/strings: Various methods and parameters use hardcoded strings and numbers, making the code less maintainable. 6. Lack of abstractions: The code could benefit from using more abstraction and design patterns to improve readability and maintainability. 7. Lack of encapsulation: The private variables in both the RemoteWasbDelegationTokenManager and WasbRemoteCallHelper classes are not properly encapsulated and could be accessed and modified by external classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RemoteWasbDelegationTokenManager implements WasbDelegationTokenManager { /** * Configuration parameter name expected in the configuration * object to provide the url of the delegation token service to fetch the delegation tokens. */ public static final String KEY_DELEGATION_TOKEN_SERVICE_URLS = "fs.azure.delegation.token.service.urls"; /** * Configuration key to enable http retry policy for delegation token service calls. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY = "fs.azure.delegationtokenservice.http.retry.policy.enabled"; /** * Configuration key for delegation token service http retry policy spec. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY = "fs.azure.delegationtokenservice.http.retry.policy.spec"; /** * Default remote delegation token manager endpoint. */ private static final String DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT = "/tokenmanager/v1"; /** * Default for delegation token service http retry policy spec. */ private static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10,3,100,2"; private static final boolean DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = true; private static final Text WASB_DT_SERVICE_NAME = new Text("WASB_DT_SERVICE"); /** * Query parameter value for Getting delegation token http request */ private static final String GET_DELEGATION_TOKEN_OP = "GETDELEGATIONTOKEN"; /** * Query parameter value for renewing delegation token http request */ private static final String RENEW_DELEGATION_TOKEN_OP = "RENEWDELEGATIONTOKEN"; /** * Query parameter value for canceling the delegation token http request */ private static final String CANCEL_DELEGATION_TOKEN_OP = "CANCELDELEGATIONTOKEN"; /** * op parameter to represent the operation. */ private static final String OP_PARAM_KEY_NAME = "op"; /** * renewer parameter to represent the renewer of the delegation token. */ private static final String RENEWER_PARAM_KEY_NAME = "renewer"; /** * service parameter to represent the service which returns delegation tokens. */ private static final String SERVICE_PARAM_KEY_NAME = "service"; /** * token parameter to represent the delegation token. */ private static final String TOKEN_PARAM_KEY_NAME = "token"; private WasbRemoteCallHelper remoteCallHelper; private String[] dtServiceUrls; private boolean isSpnegoTokenCacheEnabled; public RemoteWasbDelegationTokenManager(Configuration conf) throws IOException { RetryPolicy retryPolicy = RetryUtils.getMultipleLinearRandomRetry(conf, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT); this.isSpnegoTokenCacheEnabled = conf.getBoolean(Constants.AZURE_ENABLE_SPNEGO_TOKEN_CACHE, true); remoteCallHelper = new SecureWasbRemoteCallHelper(retryPolicy, true, isSpnegoTokenCacheEnabled); this.dtServiceUrls = conf.getTrimmedStrings(KEY_DELEGATION_TOKEN_SERVICE_URLS); if (this.dtServiceUrls == null || this.dtServiceUrls.length <= 0) { throw new IOException( KEY_DELEGATION_TOKEN_SERVICE_URLS + " config not set" + " in configuration."); } } @Override public Token getDelegationToken( String renewer) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, GET_DELEGATION_TOKEN_OP) .addParameter(RENEWER_PARAM_KEY_NAME, renewer) .addParameter(SERVICE_PARAM_KEY_NAME, WASB_DT_SERVICE_NAME.toString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpGet.METHOD_NAME); return TokenUtils.toDelegationToken(JsonUtils.parse(responseBody)); } @Override public long renewDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, RENEW_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); Map parsedResp = JsonUtils.parse(responseBody); return ((Number) parsedResp.get("long")).longValue(); } @Override public void cancelDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, CANCEL_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); remoteCallHelper.makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); } } |
blob | Long methods2 Repeated code/inconsistent naming conventions3 Feature envy: The RemoteWasbDelegationTokenManager class has access to private variables and methods (such as makeRemoteRequest()) from the WasbRemoteCallHelper class, indicating that it may be too dependent on this external class4 Duplicate code: The code for handling different operations (GETDELEGATIONTOKEN, RENEWDELEGATIONTOKEN, CANCELDELEGATIONTOKEN) is repeated in the getDelegationToken(), renewDelegationToken(), and cancelDelegationToken() methods5 Magic numbers/strings: Various methods and parameters use hardcoded strings and numbers, making the code less maintainable6 Lack of abstractions: The code could benefit from using more abstraction and design patterns to improve readability and maintainability7 Lack of encapsulation: The private variables in both the RemoteWasbDelegationTokenManager and WasbRemoteCallHelper classes are not properly encapsulated and could be accessed and modified by external classes | t | f | f | . Long methods2. Repeated code/inconsistent naming conventions3. Feature envy: The RemoteWasbDelegationTokenManager class has access to private variables and methods (such as makeRemoteRequest()) from the WasbRemoteCallHelper class, indicating that it may be too dependent on this external class.4. Duplicate code: The code for handling different operations (GETDELEGATIONTOKEN, RENEWDELEGATIONTOKEN, CANCELDELEGATIONTOKEN) is repeated in the getDelegationToken(), renewDelegationToken(), and cancelDelegationToken() methods.5. Magic numbers/strings: Various methods and parameters use hardcoded strings and numbers, making the code less maintainable.6. Lack of abstractions: The code could benefit from using more abstraction and design patterns to improve readability and maintainability.7. Lack of encapsulation: The private variables in both the RemoteWasbDelegationTokenManager and WasbRemoteCallHelper classes are not properly encapsulated and could be accessed and modified by external classes. | blob | 0 | 12080 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/security/RemoteWasbDelegationTokenManager.java/#L39-L169 | 2 | 1815 | 12080 | minor |
| 275 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.class, org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.Builder.class); } // Construct using org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); guaranteedTaskCount_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto getDefaultInstanceForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance(); } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto build() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto buildPartial() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = new org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.guaranteedTaskCount_ = guaranteedTaskCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) { return mergeFrom((org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto other) { if (other == org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance()) return this; if (other.hasGuaranteedTaskCount()) { setGuaranteedTaskCount(other.getGuaranteedTaskCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 guaranteed_task_count = 1; private int guaranteedTaskCount_ ; /** * optional int32 guaranteed_task_count = 1; */ public boolean hasGuaranteedTaskCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int32 guaranteed_task_count = 1; */ public int getGuaranteedTaskCount() { return guaranteedTaskCount_; } /** * optional int32 guaranteed_task_count = 1; */ public Builder setGuaranteedTaskCount(int value) { bitField0_ |= 0x00000001; guaranteedTaskCount_ = value; onChanged(); return this; } /** * optional int32 guaranteed_task_count = 1; */ public Builder clearGuaranteedTaskCount() { bitField0_ = (bitField0_ & ~0x00000001); guaranteedTaskCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:UpdateQueryRequestProto) } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2954 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/llap-common/src/gen/protobuf/gen-java/org/apache/hadoop/hive/llap/plugin/rpc/LlapPluginProtocolProtos.java/#L286-L435 | 1 | 275 | 2954 | minor |
| 2570 | YES, I found bad smells: the bad smells are: 1. Long method 2. Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself) 3. Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage) 4. Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Long method2 Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself)3 Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage)4 Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | t | f | f | . Long method2. Feature envy (the methods in the class are primarily accessing and manipulating instance variables rather than operating on the class itself)3. Code duplication (duplicate methods for setting and getting errorCode and rpcDataPackage)4. Lack of encapsulation (all fields are public and directly accessible, without any methods to control access) | data class | 0 | 14881 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 2570 | 14881 | minor |
| 1714 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11776 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 1714 | 11776 | minor |
| 2455 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 14522 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 2455 | 14522 | major |
| 2619 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy: The code is too long and complex, resulting in a low maintainability. Additionally, there is evidence of feature envy, where the methods in the SortableASTTransformation class are accessing and manipulating the properties of other classes, instead of just working with its own properties. This violates the principle of encapsulation and can cause confusion and difficulties in understanding the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
blob | Long method, 2Feature envy: The code is too long and complex, resulting in a low maintainability Additionally, there is evidence of feature envy, where the methods in the SortableASTTransformation class are accessing and manipulating the properties of other classes, instead of just working with its own properties This violates the principle of encapsulation and can cause confusion and difficulties in understanding the code | t | f | f | .Long method, 2.Feature envy: The code is too long and complex, resulting in a low maintainability. Additionally, there is evidence of feature envy, where the methods in the SortableASTTransformation class are accessing and manipulating the properties of other classes, instead of just working with its own properties. This violates the principle of encapsulation and can cause confusion and difficulties in understanding the code. | blob | 0 | 15051 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 2 | 2619 | 15051 | minor |
| 2734 | { "code": [ "public class OrderItem {", " private String itemName;", " private int quantity;", "", " public OrderItem(String itemName, int quantity) {", " this.itemName = itemName;", " this.quantity = quantity;", " }", "", " public double calculateTotalPrice(double itemPrice) {", " return this.quantity * itemPrice;", " }", "}" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 710 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L45156-L45191 | 1 | 2734 | 710 | major | |
| 2182 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP). 3. Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class. 4. Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future. 5. Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator". This may cause confusion for other developers. 6. Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method2 Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP)3 Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class4 Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future5 Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator" This may cause confusion for other developers 6 Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class | t | f | f | . Long method2. Feature envy: The class is extending a different class and implementing an interface, which may indicate a potential violation of the Single Responsibility Principle (SRP).3. Redundant code: The private field "KapuaId accessInfo" and its corresponding getter/setter methods are not being used anywhere in the class.4. Magic number: The serialVersionUID value is a hardcoded number and may be difficult to understand or maintain in the future.5. Inconsistent naming: The class is named "AccessRoleCreatorImpl", but it is extending a different class called "AbstractKapuaEntityCreator". This may cause confusion for other developers. 6. Unused constructor parameter: The constructor has a parameter for "scopeId", but it is not being used anywhere in the constructor or class. | data class | 0 | 13420 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 2182 | 13420 | major |
| 2647 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method | t | t | f | long method | data class | 0 | 15160 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 2647 | 15160 | major |
| 3812 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9703 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 1 | 3812 | 9703 | minor | ||
| 3774 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9458 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 | 2 | 3774 | 9458 | minor |
| 1974 | YES, found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({ "unchecked", "rawtypes" }) public final class CorePlugin extends Plugin { public static final String PLUGIN_ID = "org.eclipse.buildship.core"; //$NON-NLS-1$ public static final String GRADLE_JOB_FAMILY = PLUGIN_ID + ".jobs"; private static CorePlugin plugin; // do not use generics-aware signature since this causes compilation troubles (JDK, Spock) // search the web for -target jsr14 to find out more about this obscurity private ServiceRegistration loggerService; private ServiceRegistration publishedGradleVersionsService; private ServiceRegistration workspaceOperationsService; private ServiceRegistration internalGradleWorkspaceService; private ServiceRegistration processStreamsProviderService; private ServiceRegistration gradleLaunchConfigurationService; private ServiceRegistration listenerRegistryService; // service tracker for each service to allow to register other service implementations of the // same type but with higher prioritization, useful for testing private ServiceTracker loggerServiceTracker; private ServiceTracker publishedGradleVersionsServiceTracker; private ServiceTracker workspaceOperationsServiceTracker; private ServiceTracker internalGradleWorkspaceServiceTracker; private ServiceTracker processStreamsProviderServiceTracker; private ServiceTracker gradleLaunchConfigurationServiceTracker; private ServiceTracker listenerRegistryServiceTracker; private DefaultModelPersistence modelPersistence; private ProjectChangeListener projectChangeListener; private SynchronizingBuildScriptUpdateListener buildScriptUpdateListener; private InvocationCustomizer invocationCustomizer; private ConfigurationManager configurationManager; private DefaultExternalLaunchConfigurationManager externalLaunchConfigurationManager; private ToolingApiOperationManager operationManager; private ExtensionManager extensionManager; @Override public void start(BundleContext bundleContext) throws Exception { super.start(bundleContext); plugin = this; ensureProxySettingsApplied(); registerServices(bundleContext); } @Override public void stop(BundleContext context) throws Exception { unregisterServices(); plugin = null; super.stop(context); } private void ensureProxySettingsApplied() throws Exception { // the proxy settings are set when the core.net plugin is started Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT); } private void registerServices(BundleContext context) { // store services with low ranking such that they can be overridden // during testing or the like Dictionary preferences = new Hashtable<>(); preferences.put(Constants.SERVICE_RANKING, 1); // initialize service trackers before the services are created this.loggerServiceTracker = createServiceTracker(context, Logger.class); this.publishedGradleVersionsServiceTracker = createServiceTracker(context, PublishedGradleVersionsWrapper.class); this.workspaceOperationsServiceTracker = createServiceTracker(context, WorkspaceOperations.class); this.internalGradleWorkspaceServiceTracker = createServiceTracker(context, InternalGradleWorkspace.class); this.processStreamsProviderServiceTracker = createServiceTracker(context, ProcessStreamsProvider.class); this.gradleLaunchConfigurationServiceTracker = createServiceTracker(context, GradleLaunchConfigurationManager.class); this.listenerRegistryServiceTracker = createServiceTracker(context, ListenerRegistry.class); // register all services this.loggerService = registerService(context, Logger.class, createLogger(), preferences); this.publishedGradleVersionsService = registerService(context, PublishedGradleVersionsWrapper.class, createPublishedGradleVersions(), preferences); this.workspaceOperationsService = registerService(context, WorkspaceOperations.class, createWorkspaceOperations(), preferences); this.internalGradleWorkspaceService = registerService(context, InternalGradleWorkspace.class, createGradleWorkspace(), preferences); this.processStreamsProviderService = registerService(context, ProcessStreamsProvider.class, createProcessStreamsProvider(), preferences); this.gradleLaunchConfigurationService = registerService(context, GradleLaunchConfigurationManager.class, createGradleLaunchConfigurationManager(), preferences); this.listenerRegistryService = registerService(context, ListenerRegistry.class, createListenerRegistry(), preferences); this.modelPersistence = DefaultModelPersistence.createAndRegister(); this.projectChangeListener = ProjectChangeListener.createAndRegister(); this.buildScriptUpdateListener = SynchronizingBuildScriptUpdateListener.createAndRegister(); this.invocationCustomizer = new InvocationCustomizerCollector(); this.configurationManager = new DefaultConfigurationManager(); this.externalLaunchConfigurationManager = DefaultExternalLaunchConfigurationManager.createAndRegister(); this.operationManager = new DefaultToolingApiOperationManager(); this.extensionManager = new DefaultExtensionManager(); } private ServiceTracker createServiceTracker(BundleContext context, Class clazz) { ServiceTracker serviceTracker = new ServiceTracker(context, clazz.getName(), null); serviceTracker.open(); return serviceTracker; } private ServiceRegistration registerService(BundleContext context, Class clazz, T service, Dictionary properties) { return context.registerService(clazz.getName(), service, properties); } private EclipseLogger createLogger() { Map tracingEnablement = Maps.newHashMap(); for (TraceScope scope : CoreTraceScopes.values()) { String option = Platform.getDebugOption("org.eclipse.buildship.core/trace/" + scope.getScopeKey()); tracingEnablement.put(scope, "true".equalsIgnoreCase(option)); } return new EclipseLogger(getLog(), PLUGIN_ID, tracingEnablement); } private PublishedGradleVersionsWrapper createPublishedGradleVersions() { return new PublishedGradleVersionsWrapper(); } private WorkspaceOperations createWorkspaceOperations() { return new DefaultWorkspaceOperations(); } private InternalGradleWorkspace createGradleWorkspace() { return new DefaultGradleWorkspace(); } private ProcessStreamsProvider createProcessStreamsProvider() { return new StdProcessStreamsProvider(); } private GradleLaunchConfigurationManager createGradleLaunchConfigurationManager() { return new DefaultGradleLaunchConfigurationManager(); } private ListenerRegistry createListenerRegistry() { return new DefaultListenerRegistry(); } private void unregisterServices() { this.externalLaunchConfigurationManager.unregister(); this.buildScriptUpdateListener.close(); this.projectChangeListener.close(); this.modelPersistence.close(); this.listenerRegistryService.unregister(); this.gradleLaunchConfigurationService.unregister(); this.processStreamsProviderService.unregister(); this.internalGradleWorkspaceService.unregister(); this.workspaceOperationsService.unregister(); this.publishedGradleVersionsService.unregister(); this.loggerService.unregister(); this.listenerRegistryServiceTracker.close(); this.gradleLaunchConfigurationServiceTracker.close(); this.processStreamsProviderServiceTracker.close(); this.internalGradleWorkspaceServiceTracker.close(); this.workspaceOperationsServiceTracker.close(); this.publishedGradleVersionsServiceTracker.close(); this.loggerServiceTracker.close(); } public static CorePlugin getInstance() { return plugin; } public static Logger logger() { return (Logger) getInstance().loggerServiceTracker.getService(); } public static PublishedGradleVersionsWrapper publishedGradleVersions() { return (PublishedGradleVersionsWrapper) getInstance().publishedGradleVersionsServiceTracker.getService(); } public static WorkspaceOperations workspaceOperations() { return (WorkspaceOperations) getInstance().workspaceOperationsServiceTracker.getService(); } public static InternalGradleWorkspace internalGradleWorkspace() { return (InternalGradleWorkspace) getInstance().internalGradleWorkspaceServiceTracker.getService(); } public static ProcessStreamsProvider processStreamsProvider() { return (ProcessStreamsProvider) getInstance().processStreamsProviderServiceTracker.getService(); } public static GradleLaunchConfigurationManager gradleLaunchConfigurationManager() { return (GradleLaunchConfigurationManager) getInstance().gradleLaunchConfigurationServiceTracker.getService(); } public static ListenerRegistry listenerRegistry() { return (ListenerRegistry) getInstance().listenerRegistryServiceTracker.getService(); } public static ModelPersistence modelPersistence() { return getInstance().modelPersistence; } public static InvocationCustomizer invocationCustomizer() { return getInstance().invocationCustomizer; } public static ConfigurationManager configurationManager() { return getInstance().configurationManager; } public static ExternalLaunchConfigurationManager externalLaunchConfigurationManager() { return getInstance().externalLaunchConfigurationManager; } public static ToolingApiOperationManager operationManager() { return getInstance().operationManager; } public static ExtensionManager extensionManager() { return getInstance().extensionManager; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12619 | https://github.com/eclipse/buildship/blob/3111a7a9fe3e22d6123366686874ecd42aa2a53a/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/CorePlugin.java/#L70-L282 | 2 | 1974 | 12619 | major |
| 403 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | long method | t | t | f | long method | data class | 0 | 4118 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 403 | 4118 | major |
| 72 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1106 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 2 | 72 | 1106 | minor |
| 227 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2450 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 2 | 227 | 2450 | major |
| 789 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7520 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 789 | 7520 | major |
| 887 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8072 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 | 2 | 887 | 8072 | minor |
| 870 | {"answer": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7950 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 1 | 870 | 7950 | major |
| 5248 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class GenericConnectionStatusHtmlCreator { public static String generateConnectionViewHtml(String providerDisplayName, String providerId, UserProfile profile) { String escProviderDisplayName = escape(providerDisplayName); StringBuilder builder = new StringBuilder(); if (profile == null) { builder.append("Connect to " + escProviderDisplayName + ""); builder.append(""); builder.append(""); builder.append("You aren't connected to "); builder.append(escProviderDisplayName); builder.append(" yet. Click the button to connect with your "); builder.append(escProviderDisplayName); builder.append(" account."); builder.append(""); builder.append("Connect to "); builder.append(escProviderDisplayName); builder.append(""); builder.append(""); } else { String escProfileName = escape(profile.getName()); builder.append("Connected to "); builder.append(escProviderDisplayName); builder.append(""); builder.append("Hello, "); builder.append(escProfileName); builder.append("!You are now connected to "); builder.append(escProviderDisplayName); String username = profile.getUsername(); if (username !=null) { builder.append(" as "); builder.append(escape(username)); } builder.append("."); } return builder.toString(); } private static String escape(String in) { return htmlEscape(in).replaceAll("\\{", "{").replaceAll("\\}", "}"); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14677 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-web/src/main/java/org/springframework/social/connect/web/GenericConnectionStatusView.java/#L91-L138 | 2 | 5248 | 14677 | minor |
| 2172 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | long method | t | t | f | long method | data class | 0 | 13384 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 2172 | 13384 | minor |
| 2692 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15301 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 1 | 2692 | 15301 | minor |
| 870 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Data class 5. Dead code 6. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | Long method2 Feature envy3 Duplicate code4 Data class5 Dead code6 Inappropriate intimacy | t | f | f | . Long method2. Feature envy3. Duplicate code4. Data class5. Dead code6. Inappropriate intimacy | blob | 0 | 7950 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 2 | 870 | 7950 | major |
| 1378 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10816 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 1378 | 10816 | minor |
| 1717 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11784 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 1717 | 11784 | minor |
| 1584 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TraversalFieldAccessorFactory implements FieldAccessorFactory { @Override public boolean accept(final Neo4JPersistentProperty f) { final GraphTraversal graphEntityTraversal = f.getAnnotation(GraphTraversal.class); return graphEntityTraversal != null && graphEntityTraversal.traversalBuilder() != FieldTraversalDescriptionBuilder.class && f.getType().equals(Iterable.class); } @Override public FieldAccessor forField(final Neo4JPersistentProperty property) { return new TraversalFieldAccessor(property); } /** * @author Michael Hunger * @since 12.09.2010 */ public static class TraversalFieldAccessor implements FieldAccessor { protected final Neo4JPersistentProperty property; private final FieldTraversalDescriptionBuilder fieldTraversalDescriptionBuilder; private Class target; protected String[] params; public TraversalFieldAccessor(final Neo4JPersistentProperty property) { this.property = property; final GraphTraversal graphEntityTraversal = property.getAnnotation(GraphTraversal.class); this.target = resolveTarget(graphEntityTraversal,property); this.params = graphEntityTraversal.params(); this.fieldTraversalDescriptionBuilder = createTraversalDescription(graphEntityTraversal); } private Class resolveTarget(GraphTraversal graphTraversal, Neo4JPersistentProperty property) { if (!graphTraversal.elementClass().equals(NodeBacked.class)) return graphTraversal.elementClass(); final Class result = property.getTypeInformation().getActualType().getType(); Class[] allowedTypes={NodeBacked.class,RelationshipBacked.class,Node.class,Relationship.class, Path.class}; if (!checkTypes(result,allowedTypes)) throw new IllegalArgumentException("The target result type "+result+" of the traversal is no subclass of the allowed types: "+property+" "+allowedTypes); return result; } private boolean checkTypes(Class target, Class...allowedTypes) { for (Class type : allowedTypes) { if (type.isAssignableFrom(target)) return true; } return false; } @Override public boolean isWriteable(NodeBacked nodeBacked) { return false; } @Override public Object setValue(final NodeBacked nodeBacked, final Object newVal) { throw new InvalidDataAccessApiUsageException("Cannot set readonly traversal description field " + property); } @Override public Object getValue(final NodeBacked nodeBacked) { final TraversalDescription traversalDescription = fieldTraversalDescriptionBuilder.build(nodeBacked, property,params); return doReturn(nodeBacked.findAllByTraversal(target, traversalDescription)); } private FieldTraversalDescriptionBuilder createTraversalDescription(final GraphTraversal graphEntityTraversal) { try { final Class traversalDescriptionClass = graphEntityTraversal.traversalBuilder(); final Constructor constructor = traversalDescriptionClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating TraversalDescription from " + property,e); } } @Override public Object getDefaultImplementation() { return null; } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 11366 | https://github.com/spring-projects/spring-data-graph/blob/0210210ce436eb83bf200f5d5f9a63a440c5b27a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/fieldaccess/TraversalFieldAccessorFactory.java/#L36-L119 | 2 | 1584 | 11366 | minor |
| 944 | { "response": "YES I found bad smells", "bad smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 8474 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 944 | 8474 | major |
| 3565 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExplainTask extends Task implements Serializable { public static final String STAGE_DEPENDENCIES = "STAGE DEPENDENCIES"; private static final long serialVersionUID = 1L; public static final String EXPL_COLUMN_NAME = "Explain"; private final Set> visitedOps = new HashSet>(); private boolean isLogical = false; protected final Logger LOG; public ExplainTask() { super(); LOG = LoggerFactory.getLogger(this.getClass().getName()); } /* * Below method returns the dependencies for the passed in query to EXPLAIN. * The dependencies are the set of input tables and partitions, and are * provided back as JSON output for the EXPLAIN command. * Example output: * {"input_tables":[{"tablename": "default@test_sambavi_v1", "tabletype": "TABLE"}], * "input partitions":["default@srcpart@ds=2008-04-08/hr=11"]} */ @VisibleForTesting static JSONObject getJSONDependencies(ExplainWork work) throws Exception { assert(work.getDependency()); JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); JSONArray inputTableInfo = new JSONArray(); JSONArray inputPartitionInfo = new JSONArray(); for (ReadEntity input: work.getInputs()) { switch (input.getType()) { case TABLE: Table table = input.getTable(); JSONObject tableInfo = new JSONObject(); tableInfo.put("tablename", table.getCompleteName()); tableInfo.put("tabletype", table.getTableType().toString()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { tableInfo.put("tableParents", input.getParents().toString()); } inputTableInfo.put(tableInfo); break; case PARTITION: JSONObject partitionInfo = new JSONObject(); partitionInfo.put("partitionName", input.getPartition().getCompleteName()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { partitionInfo.put("partitionParents", input.getParents().toString()); } inputPartitionInfo.put(partitionInfo); break; default: break; } } outJSONObject.put("input_tables", inputTableInfo); outJSONObject.put("input_partitions", inputPartitionInfo); return outJSONObject; } public JSONObject getJSONCBOPlan(PrintStream out, ExplainWork work) throws Exception { JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); String cboPlan = work.getCboPlan(); if (cboPlan != null) { if (jsonOutput) { outJSONObject.put("CBOPlan", cboPlan); } else { out.println("CBO PLAN:"); out.println(cboPlan); } } return outJSONObject; } public JSONObject getJSONLogicalPlan(PrintStream out, ExplainWork work) throws Exception { isLogical = true; JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } if (work.getParseContext() != null) { if (out != null) { out.print("LOGICAL PLAN:"); } JSONObject jsonPlan = outputMap(work.getParseContext().getTopOps(), true, out, work.getExtended(), jsonOutput, 0); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("LOGICAL PLAN", jsonPlan); } } else { System.err.println("No parse context!"); } return outJSONObject; } private static String trueCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS true"; private static String falseCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS false"; @VisibleForTesting ImmutablePair outputPlanVectorization(PrintStream out, boolean jsonOutput) throws Exception { if (out != null) { out.println("PLAN VECTORIZATION:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; HiveConf hiveConf = queryState.getConf(); boolean isVectorizationEnabled = HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED); String isVectorizationEnabledCondName = (isVectorizationEnabled ? trueCondNameVectorizationEnabled : falseCondNameVectorizationEnabled); List isVectorizationEnabledCondList = Arrays.asList(isVectorizationEnabledCondName); if (out != null) { out.print(indentString(2)); out.print("enabled: "); out.println(isVectorizationEnabled); out.print(indentString(2)); if (!isVectorizationEnabled) { out.print("enabledConditionsNotMet: "); } else { out.print("enabledConditionsMet: "); } out.println(isVectorizationEnabledCondList); } if (jsonOutput) { json.put("enabled", isVectorizationEnabled); JSONArray jsonArray = new JSONArray(Arrays.asList(isVectorizationEnabledCondName)); if (!isVectorizationEnabled) { json.put("enabledConditionsNotMet", jsonArray); } else { json.put("enabledConditionsMet", jsonArray); } } return new ImmutablePair(isVectorizationEnabled, jsonOutput ? json : null); } public JSONObject getJSONPlan(PrintStream out, ExplainWork work) throws Exception { return getJSONPlan(out, work.getRootTasks(), work.getFetchTask(), work.isFormatted(), work.getExtended(), work.isAppendTaskType(), work.getCboInfo(), work.getOptimizedSQL()); } public JSONObject getJSONPlan(PrintStream out, List> tasks, Task fetchTask, boolean jsonOutput, boolean isExtended, boolean appendTaskType, String cboInfo, String optimizedSQL) throws Exception { // If the user asked for a formatted output, dump the json output // in the output stream JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); if (jsonOutput) { out = null; } if (optimizedSQL != null) { if (jsonOutput) { outJSONObject.put("optimizedSQL", optimizedSQL); } else { out.print("OPTIMIZED SQL: "); out.println(optimizedSQL); } } List ordered = StageIDsRearranger.getExplainOrder(conf, tasks); if (fetchTask != null) { fetchTask.setParentTasks((List)StageIDsRearranger.getFetchSources(tasks)); if (fetchTask.getNumParent() == 0) { fetchTask.setRootTask(true); } ordered.add(fetchTask); } boolean suppressOthersForVectorization = false; if (this.work != null && this.work.isVectorization()) { ImmutablePair planVecPair = outputPlanVectorization(out, jsonOutput); if (this.work.isVectorizationOnly()) { // Suppress the STAGES if vectorization is off. suppressOthersForVectorization = !planVecPair.left; } if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("PLAN VECTORIZATION", planVecPair.right); } } if (!suppressOthersForVectorization) { JSONObject jsonDependencies = outputDependencies(out, jsonOutput, appendTaskType, ordered); if (out != null) { out.println(); } if (jsonOutput) { if (cboInfo != null) { outJSONObject.put("cboInfo", cboInfo); } outJSONObject.put(STAGE_DEPENDENCIES, jsonDependencies); } // Go over all the tasks and dump out the plans JSONObject jsonPlan = outputStagePlans(out, ordered, jsonOutput, isExtended); if (jsonOutput) { outJSONObject.put("STAGE PLANS", jsonPlan); } if (fetchTask != null) { fetchTask.setParentTasks(null); } } return jsonOutput ? outJSONObject : null; } private List toString(Collection objects) { List list = new ArrayList(); for (Object object : objects) { list.add(String.valueOf(object)); } return list; } private Object toJson(String header, String message, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return message; } out.print(header); out.println(": "); out.print(indentString(2)); out.println(message); return null; } private Object toJson(String header, List messages, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return new JSONArray(messages); } out.print(header); out.println(": "); for (String message : messages) { out.print(indentString(2)); out.print(message); out.println(); } return null; } private JSONObject getLocks(PrintStream out, ExplainWork work) { JSONObject jsonObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } List lockComponents = AcidUtils.makeLockComponents(work.getOutputs(), work.getInputs(), conf); if (null != out) { out.print("LOCK INFORMATION:\n"); } List locks = new ArrayList<>(lockComponents.size()); for (LockComponent component : lockComponents) { ExplainLockDesc lockDesc = new ExplainLockDesc(component); if (null != out) { out.print(lockDesc.getFullName()); out.print(" -> "); out.print(lockDesc.getLockType()); out.print('\n'); } else { locks.add(lockDesc); } } if (jsonOutput) { jsonObject.put("LOCK INFORMATION:", locks); } return jsonObject; } @Override public int execute(DriverContext driverContext) { PrintStream out = null; try { Path resFile = work.getResFile(); OutputStream outS = resFile.getFileSystem(conf).create(resFile); out = new PrintStream(outS); if (work.isCbo()) { JSONObject jsonCBOPlan = getJSONCBOPlan(out, work); if (work.isFormatted()) { out.print(jsonCBOPlan); } } else if (work.isLogical()) { JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work); if (work.isFormatted()) { out.print(jsonLogicalPlan); } } else if (work.isAuthorize()) { JSONObject jsonAuth = collectAuthRelatedEntities(out, work); if (work.isFormatted()) { out.print(jsonAuth); } } else if (work.getDependency()) { JSONObject jsonDependencies = getJSONDependencies(work); out.print(jsonDependencies); } else if (work.isLocks()) { JSONObject jsonLocks = getLocks(out, work); if(work.isFormatted()) { out.print(jsonLocks); } } else if (work.isAst()) { // Print out the parse AST if (work.getAstStringTree() != null) { outputAST(work.getAstStringTree(), out, work.isFormatted(), 0); } } else { if (work.isUserLevelExplain()) { // Because of the implementation of the JsonParserFactory, we are sure // that we can get a TezJsonParser. JsonParser jsonParser = JsonParserFactory.getParser(conf); work.getConfig().setFormatted(true); JSONObject jsonPlan = getJSONPlan(out, work); if (work.getCboInfo() != null) { jsonPlan.put("cboInfo", work.getCboInfo()); } try { jsonParser.print(jsonPlan, out); } catch (Exception e) { // if there is anything wrong happen, we bail out. LOG.error("Running explain user level has problem." + " Falling back to normal explain.", e); work.getConfig().setFormatted(false); work.getConfig().setUserLevelExplain(false); jsonPlan = getJSONPlan(out, work); } } else { JSONObject jsonPlan = getJSONPlan(out, work); if (work.isFormatted()) { // use the parser to get the output operators of RS JsonParser jsonParser = JsonParserFactory.getParser(conf); if (jsonParser != null) { jsonParser.print(jsonPlan, null); LOG.info("JsonPlan is augmented to {}", jsonPlan); } out.print(jsonPlan); } } } out.close(); out = null; return (0); } catch (Exception e) { LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e)); setException(e); return (1); } finally { IOUtils.closeStream(out); } } @VisibleForTesting JSONObject collectAuthRelatedEntities(PrintStream out, ExplainWork work) throws Exception { BaseSemanticAnalyzer analyzer = work.getAnalyzer(); HiveOperation operation = queryState.getHiveOperation(); JSONObject object = new JSONObject(new LinkedHashMap<>()); Object jsonInput = toJson("INPUTS", toString(analyzer.getInputs()), out, work); if (work.isFormatted()) { object.put("INPUTS", jsonInput); } Object jsonOutput = toJson("OUTPUTS", toString(analyzer.getOutputs()), out, work); if (work.isFormatted()) { object.put("OUTPUTS", jsonOutput); } String userName = SessionState.get().getAuthenticator().getUserName(); Object jsonUser = toJson("CURRENT_USER", userName, out, work); if (work.isFormatted()) { object.put("CURRENT_USER", jsonUser); } Object jsonOperation = toJson("OPERATION", operation.name(), out, work); if (work.isFormatted()) { object.put("OPERATION", jsonOperation); } if (analyzer.skipAuthorization()) { return object; } final List exceptions = new ArrayList(); Object delegate = SessionState.get().getActiveAuthorizer(); if (delegate != null) { Class itface = SessionState.get().getAuthorizerInterface(); Object authorizer = AuthorizationFactory.create(delegate, itface, new AuthorizationFactory.AuthorizationExceptionHandler() { @Override public void exception(Exception exception) { exceptions.add(exception.getMessage()); } }); SessionState.get().setActiveAuthorizer(authorizer); try { Driver.doAuthorization(queryState.getHiveOperation(), analyzer, ""); } finally { SessionState.get().setActiveAuthorizer(delegate); } } if (!exceptions.isEmpty()) { Object jsonFails = toJson("AUTHORIZATION_FAILURES", exceptions, out, work); if (work.isFormatted()) { object.put("AUTHORIZATION_FAILURES", jsonFails); } } return object; } private static String indentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.append(" "); } return sb.toString(); } @VisibleForTesting JSONObject outputMap(Map mp, boolean hasHeader, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { TreeMap tree = getBasictypeKeyedMap(mp); JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null && hasHeader && !mp.isEmpty()) { out.println(); } for (Entry ent : tree.entrySet()) { // Print the key if (out != null) { out.print(indentString(indent)); out.print(ent.getKey()); out.print(" "); } // Print the value if (isPrintable(ent.getValue())) { if (out != null) { out.print(ent.getValue()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() instanceof List) { if (ent.getValue() != null && !((List)ent.getValue()).isEmpty() && ((List)ent.getValue()).get(0) != null && ((List)ent.getValue()).get(0) instanceof TezWork.Dependency) { if (out != null) { boolean isFirst = true; for (TezWork.Dependency dep: (List)ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getType()); out.print(")"); } out.println(); } if (jsonOutput) { for (TezWork.Dependency dep: (List)ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getType()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else if (ent.getValue() != null && !((List) ent.getValue()).isEmpty() && ((List) ent.getValue()).get(0) != null && ((List) ent.getValue()).get(0) instanceof SparkWork.Dependency) { if (out != null) { boolean isFirst = true; for (SparkWork.Dependency dep: (List) ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getShuffleType()); out.print(", "); out.print(dep.getNumPartitions()); out.print(")"); } out.println(); } if (jsonOutput) { for (SparkWork.Dependency dep: (List) ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getShuffleType()); jsonDep.put("partitions", dep.getNumPartitions()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } } else if (ent.getValue() instanceof Map) { String stringValue = getBasictypeKeyedMap((Map)ent.getValue()).toString(); if (out != null) { out.print(stringValue); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), stringValue); } } else if (ent.getValue() != null) { if (out != null) { out.println(); } JSONObject jsonOut = outputPlan(ent.getValue(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (jsonOutput) { json.put(ent.getKey().toString(), jsonOut); } } else { if (out != null) { out.println(); } } } return jsonOutput ? json : null; } /** * Retruns a map which have either primitive or string keys. * * This is neccessary to discard object level comparators which may sort the objects based on some non-trivial logic. * * @param mp * @return */ private TreeMap getBasictypeKeyedMap(Map mp) { TreeMap ret = new TreeMap(); if (mp.size() > 0) { Object firstKey = mp.keySet().iterator().next(); if (firstKey.getClass().isPrimitive() || firstKey instanceof String) { // keep it as-is ret.putAll(mp); return ret; } else { for (Entry entry : mp.entrySet()) { // discard possibly type related sorting order and replace with alphabetical ret.put(entry.getKey().toString(), entry.getValue()); } } } return ret; } private JSONArray outputList(List l, PrintStream out, boolean hasHeader, boolean extended, boolean jsonOutput, int indent, boolean inTest) throws Exception { boolean first_el = true; boolean nl = false; JSONArray outputArray = new JSONArray(); for (Object o : l) { if (isPrintable(o)) { String delim = first_el ? " " : ", "; if (out != null) { out.print(delim); out.print(o); } if (jsonOutput) { outputArray.put(o); } nl = true; } else { if (first_el && (out != null) && hasHeader) { out.println(); } JSONObject jsonOut = outputPlan(o, out, extended, jsonOutput, jsonOutput ? 0 : (hasHeader ? indent + 2 : indent), "", inTest); if (jsonOutput) { outputArray.put(jsonOut); } } first_el = false; } if (nl && (out != null)) { out.println(); } return jsonOutput ? outputArray : null; } private boolean isPrintable(Object val) { if (val instanceof Boolean || val instanceof String || val instanceof Integer || val instanceof Long || val instanceof Byte || val instanceof Float || val instanceof Double || val instanceof Path) { return true; } if (val != null && val.getClass().isPrimitive()) { return true; } return false; } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, ""); } private boolean isInvokeVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // The EXPLAIN VECTORIZATION option was specified. final boolean desireOnly = this.work.isVectorizationOnly(); final VectorizationDetailLevel desiredVecDetailLevel = this.work.isVectorizationDetailLevel(); switch (vectorization) { case NON_VECTORIZED: // Display all non-vectorized leaf objects unless ONLY. if (desireOnly) { invokeFlag = false; } break; case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: if (vectorization.rank < desiredVecDetailLevel.rank) { // This detail not desired. invokeFlag = false; } break; case SUMMARY_PATH: case OPERATOR_PATH: if (desireOnly) { if (vectorization.rank < desiredVecDetailLevel.rank) { // Suppress headers and all objects below. invokeFlag = false; } } break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } private boolean isInvokeNonVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // Do not display vectorization objects. switch (vectorization) { case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: invokeFlag = false; break; case NON_VECTORIZED: // No action. break; case SUMMARY_PATH: case OPERATOR_PATH: // Always include headers since they contain non-vectorized objects, too. break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } @VisibleForTesting JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, appendToHeader, queryState.getConf().getBoolVar(ConfVars.HIVE_IN_TEST)); } public JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader, boolean inTest) throws Exception { // Check if work has an explain annotation Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class); String keyJSONObject = null; if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } if (invokeFlag) { keyJSONObject = xpl_note.displayName(); if (out != null) { out.print(indentString(indent)); if (appendToHeader != null && !appendToHeader.isEmpty()) { out.println(xpl_note.displayName() + appendToHeader); } else { out.println(xpl_note.displayName()); } } } } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; // If this is an operator then we need to call the plan generation on the // conf and then the children if (work instanceof Operator) { Operator operator = (Operator) work; if (operator.getConf() != null) { String appender = isLogical ? " (" + operator.getOperatorId() + ")" : ""; JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput, jsonOutput ? 0 : indent, appender, inTest); if (this.work != null && (this.work.isUserLevelExplain() || this.work.isFormatted())) { if (jsonOut != null && jsonOut.length() > 0) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:", operator.getOperatorId()); } if (!this.work.isUserLevelExplain() && this.work.isFormatted() && operator.getConf() instanceof ReduceSinkDesc ) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("outputname:", ((ReduceSinkDesc) operator.getConf()).getOutputName()); } } if (jsonOutput) { json = jsonOut; } } if (!visitedOps.contains(operator) || !isLogical) { visitedOps.add(operator); if (operator.getChildOperators() != null) { int cindent = jsonOutput ? 0 : indent + 2; for (Operator op : operator.getChildOperators()) { JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent, "", inTest); if (jsonOutput) { ((JSONObject)json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut); } } } } if (jsonOutput) { return json; } return null; } // We look at all methods that generate values for explain Method[] methods = work.getClass().getMethods(); Arrays.sort(methods, new MethodComparator()); for (Method m : methods) { int prop_indents = jsonOutput ? 0 : indent + 2; note = AnnotationUtils.getAnnotation(m, Explain.class); if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (invokeFlag) { if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } } if (invokeFlag) { Object val = null; try { if(postProcess(xpl_note)) { val = m.invoke(work, inTest); } else{ val = m.invoke(work); } } catch (InvocationTargetException ex) { // Ignore the exception, this may be caused by external jars val = null; } if (val == null) { continue; } if(xpl_note.jsonOnly() && !jsonOutput) { continue; } String header = null; boolean skipHeader = xpl_note.skipHeader(); boolean emptyHeader = false; if (!xpl_note.displayName().equals("")) { header = indentString(prop_indents) + xpl_note.displayName() + ":"; } else { emptyHeader = true; prop_indents = indent; header = indentString(prop_indents); } // Try the output as a primitive object if (isPrintable(val)) { if (out != null && shouldPrint(xpl_note, val)) { if (!skipHeader) { out.print(header); out.print(" "); } out.println(val); } if (jsonOutput && shouldPrint(xpl_note, val)) { json.put(header, val.toString()); } continue; } int ind = 0; if (!jsonOutput) { if (!skipHeader) { ind = prop_indents + 2; } else { ind = indent; } } // Try this as a map if (val instanceof Map) { // Go through the map and print out the stuff Map mp = (Map) val; if (out != null && !skipHeader && mp != null && !mp.isEmpty()) { out.print(header); } JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput, ind); if (jsonOutput && !mp.isEmpty()) { json.put(header, jsonOut); } continue; } // Try this as a list if (val instanceof List || val instanceof Set) { List l = val instanceof List ? (List)val : new ArrayList((Set)val); if (out != null && !skipHeader && l != null && !l.isEmpty()) { out.print(header); } JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput, ind, inTest); if (jsonOutput && !l.isEmpty()) { json.put(header, jsonOut); } continue; } // Finally check if it is serializable try { if (!skipHeader && out != null) { out.println(header); } JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind, "", inTest); if (jsonOutput && jsonOut != null && jsonOut.length() != 0) { if (!skipHeader) { json.put(header, jsonOut); } else { for(String k: JSONObject.getNames(jsonOut)) { json.put(k, jsonOut.get(k)); } } } continue; } catch (ClassCastException ce) { // Ignore } } } } if (jsonOutput) { if (keyJSONObject != null) { JSONObject ret = new JSONObject(new LinkedHashMap<>()); ret.put(keyJSONObject, json); return ret; } return json; } return null; } /** * use case: this is only use for testing purposes. For instance, we might * want to sort the expressions in a filter so we get deterministic comparable * golden files */ private boolean postProcess(Explain exp) { return exp.postProcess(); } /** * use case: we want to print the object in explain only if it is true * how to do : print it unless the following 3 are all true: * 1. displayOnlyOnTrue tag is on * 2. object is boolean * 3. object is false * @param exp * @param val * @return */ private boolean shouldPrint(Explain exp, Object val) { if (exp.displayOnlyOnTrue() && (val instanceof Boolean) & !((Boolean)val)) { return false; } return true; } private JSONObject outputPlan(Task task, PrintStream out, JSONObject parentJSON, boolean extended, boolean jsonOutput, int indent) throws Exception { if (out != null) { out.print(indentString(indent)); out.print("Stage: "); out.print(task.getId()); out.print("\n"); } // Start by getting the work part of the task and call the output plan for // the work JSONObject jsonOutputPlan = outputPlan(task.getWork(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (out != null) { out.println(); } if (jsonOutput) { parentJSON.put(task.getId(), jsonOutputPlan); } return null; } @VisibleForTesting JSONObject outputDependencies(Task task, PrintStream out, JSONObject parentJson, boolean jsonOutput, boolean taskType, int indent) throws Exception { boolean first = true; JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null) { out.print(indentString(indent)); out.print(task.getId()); } if ((task.getParentTasks() == null || task.getParentTasks().isEmpty())) { if (task.isRootTask()) { if (out != null) { out.print(" is a root stage"); } if (jsonOutput) { json.put("ROOT STAGE", "TRUE"); } } } else { StringBuilder s = new StringBuilder(); first = true; for (Task parent : task.getParentTasks()) { if (!first) { s.append(", "); } first = false; s.append(parent.getId()); } if (out != null) { out.print(" depends on stages: "); out.print(s.toString()); } if (jsonOutput) { json.put("DEPENDENT STAGES", s.toString()); } } Task currBackupTask = task.getBackupTask(); if (currBackupTask != null) { if (out != null) { out.print(" has a backup stage: "); out.print(currBackupTask.getId()); } if (jsonOutput) { json.put("BACKUP STAGE", currBackupTask.getId()); } } if (task instanceof ConditionalTask && ((ConditionalTask) task).getListTasks() != null) { StringBuilder s = new StringBuilder(); first = true; for (Task con : ((ConditionalTask) task).getListTasks()) { if (!first) { s.append(", "); } first = false; s.append(con.getId()); } if (out != null) { out.print(" , consists of "); out.print(s.toString()); } if (jsonOutput) { json.put("CONDITIONAL CHILD TASKS", s.toString()); } } if (taskType) { if (out != null) { out.print(" ["); out.print(task.getType()); out.print("]"); } if (jsonOutput) { json.put("TASK TYPE", task.getType().name()); } } if (out != null) { out.println(); } return jsonOutput ? json : null; } public String outputAST(String treeString, PrintStream out, boolean jsonOutput, int indent) throws JSONException { if (out != null) { out.print(indentString(indent)); out.println("ABSTRACT SYNTAX TREE:"); out.print(indentString(indent + 2)); out.println(treeString); } return jsonOutput ? treeString : null; } public JSONObject outputDependencies(PrintStream out, boolean jsonOutput, boolean appendTaskType, List tasks) throws Exception { if (out != null) { out.println(STAGE_DEPENDENCIES + ":"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { JSONObject jsonOut = outputDependencies(task, out, json, jsonOutput, appendTaskType, 2); if (jsonOutput && jsonOut != null) { json.put(task.getId(), jsonOut); } } return jsonOutput ? json : null; } public JSONObject outputStagePlans(PrintStream out, List tasks, boolean jsonOutput, boolean isExtended) throws Exception { if (out != null) { out.println("STAGE PLANS:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { outputPlan(task, out, json, isExtended, jsonOutput, 2); } return jsonOutput ? json : null; } /** * MethodComparator. * */ public class MethodComparator implements Comparator { @Override public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } } @Override public StageType getType() { return StageType.EXPLAIN; } @Override public String getName() { return "EXPLAIN"; } public static List getResultSchema() { FieldSchema tmpFieldSchema = new FieldSchema(); List colList = new ArrayList(); tmpFieldSchema.setName(EXPL_COLUMN_NAME); tmpFieldSchema.setType(STRING_TYPE_NAME); colList.add(tmpFieldSchema); return colList; } @Override public boolean canExecuteInParallel() { return false; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 7829 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/ExplainTask.java/#L84-L1302 | 2 | 3565 | 7829 | critical |
| 5381 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15120 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 5381 | 15120 | minor |
| 5379 | {"output":"YES I found bad smells","bad smells are":["Long Method","Data Class","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Scanner { private final List tokens; private int currentPosition = 0; public Scanner(final List tokens) { this.tokens = tokens; } public NodeSelect scan() { return scanSelect(); } public void checkTail() { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && (item1.getNodeType() != NodeType.OPERATION || item1.getValue().length() != 0)) { currentPosition = num1; throwSyntaxError(SyntaxError.EXPECTING_END_OF_STRING); } } private NodeSelect scanSelect() { final Node node1 = ensureToken(NodeType.NAME, "select", SyntaxError.EXPECTING_SELECT); //$NON-NLS-1$ final NodeSelect select1 = new NodeSelect(); if (scanToken(NodeType.OPERATION, "*") != null) //$NON-NLS-1$ { select1.setFields(null); } else { select1.setFields(scanFieldNameList(false, NodeType.FIELD_LIST)); } while (true) { if (scanToken(NodeType.NAME, "from") != null) //$NON-NLS-1$ { if (select1.getFrom() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_FROM); } select1.setFrom(scanTableName()); continue; } if (scanToken(NodeType.NAME, "where") != null) //$NON-NLS-1$ { if (select1.getWhere() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_WHERE); } select1.setWhere(scanWhere(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getGroupBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_GROUP_BY); } select1.setGroupBy(scanFieldNameList(false, NodeType.GROUP_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "order") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getOrderBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_ORDER_BY); } select1.setOrderBy(scanFieldNameList(true, NodeType.ORDER_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "asof") != null) //$NON-NLS-1$ { if (select1.getAsOf() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_AS_OF); } select1.setAsOf(scanValue(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "mode") != null) //$NON-NLS-1$ { if (select1.getMode() != null) { currentPosition--; throwSyntaxError(SyntaxError.DUPLICATE_MODE); } select1.setMode(ScanMode()); continue; } select1.setStartOffset(node1.getStartOffset()); select1.setEndOffset(((NodeItem) tokens.get(tokens.size() - 1)).getEndOffset()); return select1; } } private Node scanWhere(final NodeTableName table) { return scanCondition4(table); } private Node scanCondition4(final NodeTableName table) { Node node1 = scanCondition3(table); NodeOrOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "or"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "||"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeOrOperator(); operator1.add(node1); } operator1.add(scanCondition3(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition3(final NodeTableName table) { Node node1 = scanCondition2(table); NodeAndOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "and"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "&&"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeAndOperator(); operator1.add(node1); } operator1.add(scanCondition2(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition2(final NodeTableName table) { Node node1 = scanToken(NodeType.NAME, "not"); //$NON-NLS-1$ if (node1 == null) { node1 = scanToken(NodeType.OPERATION, "!"); //$NON-NLS-1$ } if (node1 != null) { final Node node2 = scanCondition2(table); final Node node3 = new NodeNotOperator(node2); node3.setStartOffset(node1.getStartOffset()); node3.setEndOffset(node2.getEndOffset()); return node3; } node1 = scanToken(NodeType.NAME, "ever"); //$NON-NLS-1$ if (node1 != null) { final Node node4 = scanCondition2(table); final Node node5 = new NodeEverOperator(node4); node5.setStartOffset(node1.getStartOffset()); node5.setEndOffset(node4.getEndOffset()); return node5; } node1 = scanToken(NodeType.NAME, "never"); //$NON-NLS-1$ if (node1 != null) { final Node node6 = scanCondition2(table); final Node node7 = new NodeNotOperator(new NodeEverOperator(node6)); node7.setStartOffset(node1.getStartOffset()); node7.setEndOffset(node6.getEndOffset()); return node7; } return scanCondition1(table); } private Node scanCondition1(final NodeTableName table) { final Node node1 = scanToken(NodeType.OPERATION, "("); //$NON-NLS-1$ if (node1 != null) { final Node node2 = scanWhere(table); final Node node3 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ node2.setStartOffset(node1.getStartOffset()); node2.setEndOffset(node3.getEndOffset()); node2.setHasParantheses(true); return node2; } final NodeCondition condition1 = new NodeCondition(); Node node4 = condition1; condition1.setLeft(scanFieldName(table)); final Stack stack1 = new Stack(); while (true) { if (scanToken(NodeType.NAME, "not") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); continue; } if (scanToken(NodeType.NAME, "ever") != null) //$NON-NLS-1$ { stack1.push(NodeType.EVER); continue; } if (scanToken(NodeType.NAME, "never") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); stack1.push(NodeType.EVER); continue; } break; } while (true) { if (stack1.size() <= 0) { condition1.setCondition(scanConditionOperator(node4 != condition1)); if (condition1.getCondition() == Condition.NONE) { throwSyntaxError(SyntaxError.EXPECTING_COMPARISON_OPERATOR); } if (condition1.getCondition() == Condition.GROUP) { condition1.setRight(scanValue(table)); } else if (condition1.getCondition() == Condition.IN) { final Node node5 = ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final Node node6 = scanValueList(table); final Node node7 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ node6.setStartOffset(node5.getStartOffset()); node6.setEndOffset(node7.getEndOffset()); condition1.setRight(node6); } else if (condition1.getCondition() == Condition.UNDER) { condition1.setRight(scanValue(table)); } else { Node node8 = TryScanFieldName(); if (node8 == null) { node8 = TryScanExpression(); } if (node8 != null) { condition1.setRight(node8); } else { throwSyntaxError(SyntaxError.EXPECTING_FIELD_OR_EXPRESSION); } } node4.setStartOffset(condition1.getLeft().getStartOffset()); node4.setEndOffset(condition1.getRight().getEndOffset()); return node4; } final NodeType nodeType = stack1.pop(); if (nodeType == NodeType.NOT) { node4 = new NodeNotOperator(node4); } else if (nodeType == NodeType.EVER) { node4 = new NodeEverOperator(node4); } } } private Node scanValueList(final NodeTableName table) { final NodeValueList list1 = new NodeValueList(); do { list1.add(scanExpression(table)); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ list1.setStartOffset(list1.getItem(0).getStartOffset()); list1.setEndOffset(list1.getItem(list1.getCount() - 1).getEndOffset()); return list1; } private Node scanValue(final NodeTableName table) { final Node node = TryScanSingleValue(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); } return node; } private Node scanExpression(final NodeTableName nodeTable) { final Node node = TryScanExpression(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); return null; } return node; } private Condition scanConditionOperator(final boolean afterNotOrEver) { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && ((item1.getNodeType() == NodeType.NAME) || ((item1.getNodeType() == NodeType.OPERATION) && !afterNotOrEver))) { Condition condition1 = ConditionalOperators.find(item1.getValue()); if (condition1 == Condition.IN && scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { condition1 = Condition.GROUP; } else if (condition1 == Condition.CONTAINS && scanToken(NodeType.NAME, "words") != null) //$NON-NLS-1$ { condition1 = Condition.CONTAINS_WORDS; } if (condition1 != Condition.NONE) { return condition1; } } currentPosition = num1; if (!afterNotOrEver) { return Condition.NONE; } return Condition.EQUALS; } private NodeTableName scanTableName() { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == NodeType.NAME) { return new NodeTableName((NodeName) tokenNode); } currentPosition = savedCurrentPosition; throwSyntaxError(SyntaxError.EXPECTING_TABLE_NAME); return null; } // direction is true if each field name in the field name list can be // suffixed by an optional // direction indicator - asc or desc private NodeFieldList scanFieldNameList(final boolean direction, final NodeType nodeType) { final NodeFieldList fieldListNode = new NodeFieldList(nodeType); while (true) { final NodeFieldName fieldNameNode = scanFieldName(null); if (direction) { if (scanToken(NodeType.NAME, "asc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.ASCENDING); } else if (scanToken(NodeType.NAME, "desc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.DESCENDING); } } fieldListNode.add(fieldNameNode); /* * if the next token is not a comma operator, then the field list is * finished */ if (scanToken(NodeType.OPERATION, ",") == null) //$NON-NLS-1$ { if (fieldListNode.getCount() != 0) { /* * if the field list node is not empty, set it's start and * end offset by using the starting and ending node in the * list */ fieldListNode.setStartOffset(fieldListNode.getItem(0).getStartOffset()); fieldListNode.setEndOffset(fieldListNode.getItem(fieldListNode.getCount() - 1).getEndOffset()); } return fieldListNode; } } } private NodeFieldName scanFieldName(final NodeTableName table) { final Node node = TryScanFieldName(); if (node != null) { return (NodeFieldName) node; } throwSyntaxError(SyntaxError.EXPECTING_FIELD_NAME); return null; } private NodeMode ScanMode() { ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final NodeMode mode = new NodeMode(); do { final int pos = currentPosition; final NodeItem item = nextToken(); if ((item == null) || !(item.getNodeType().equals(NodeType.NAME))) { currentPosition = pos; throwSyntaxError(SyntaxError.EXPECTING_MODE); return null; } mode.add(item); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ mode.setStartOffset(mode.getItem(0).getStartOffset()); mode.setEndOffset(mode.getItem(mode.getCount() - 1).getEndOffset()); return mode; } private NodeItem ensureToken(final NodeType type, final String str, final SyntaxError syntaxError) { final NodeItem tokenNode = scanToken(type, str); if (tokenNode == null) { throwSyntaxError(syntaxError); } return tokenNode; } private void throwSyntaxError(final SyntaxError error) { NodeItem causeNode = null; if (currentPosition < tokens.size()) { causeNode = (NodeItem) tokens.get(currentPosition); } throw new SyntaxException(causeNode, error); } private NodeItem scanToken(final NodeType type, final String str) { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == type && str.equalsIgnoreCase(tokenNode.getValue())) { return tokenNode; } currentPosition = savedCurrentPosition; return null; } private NodeItem nextToken() { if (currentPosition < tokens.size()) { return (NodeItem) tokens.get(currentPosition++); } return null; } private Node TryScanExpression() { int num; Node node = TryScanSingleValue(); if (node == null) { return null; } while (true) { num = currentPosition; final NodeItem item = nextToken(); if (item != null) { Arithmetic none = Arithmetic.NONE; Node node2 = null; if (item.getNodeType() == NodeType.NUMBER) { none = ArithmeticalOperators.find(item.getValue().substring(0, 1)); if (none != Arithmetic.NONE) { item.setValue(item.getValue().substring(1)); node2 = item; } } else if (item.getNodeType() == NodeType.OPERATION) { none = ArithmeticalOperators.find(item.getValue()); if (none != Arithmetic.NONE) { node2 = TryScanSingleValue(); } } if ((none != Arithmetic.NONE) && (node2 != null)) { final NodeArithmetic arithmetic2 = new NodeArithmetic(); arithmetic2.setArithmetic(none); arithmetic2.setLeft(node); arithmetic2.setRight(node2); arithmetic2.setStartOffset(arithmetic2.getLeft().getStartOffset()); arithmetic2.setEndOffset(arithmetic2.getRight().getEndOffset()); node = arithmetic2; continue; } } currentPosition = num; return node; } } private Node TryScanFieldName() { Node node = null; final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (node2.getNodeType() == NodeType.NAME)) { final NodeItem item = scanToken(NodeType.OPERATION, "."); //$NON-NLS-1$ Node node3 = null; if (item != null) { node3 = nextToken(); if ((node3 != null) && (node3.getNodeType() == NodeType.NAME)) { node = new NodeFieldName((NodeName) node2, (NodeName) node3); } } else { node = new NodeFieldName((NodeName) node2); } } if (node == null) { currentPosition = pos; return null; } return node; } private Node TryScanSingleValue() { final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (((node2.getNodeType() == NodeType.NUMBER) || (node2.getNodeType() == NodeType.STRING)) || ((node2.getNodeType() == NodeType.VARIABLE) || (node2.getNodeType() == NodeType.BOOL_VALUE)))) { return node2; } currentPosition = pos; return null; } } |
blob | "YES I found bad smells","bad smells are" | t | f | f | "YES I found bad smells", "bad smells are" | blob | 0 | 15115 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/workitem/internal/wiqlparse/Scanner.java/#L9-L514 | 1 | 5379 | 15115 | minor |
| 1286 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10611 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 1286 | 10611 | critical |
| 2698 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | long method | t | t | f | long method | blob | 0 | 15324 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 1 | 2698 | 15324 | minor |
| 2339 | {"response": "YES I found bad smells the bad smells are: 1. Long method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | Long method, 2 Data Class"} | t | f | f | . Long method, 2. Data Class"} | blob | 0 | 14172 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 1 | 2339 | 14172 | minor |
| 2143 | { "message": "YES I found bad smells", "the bad smells are:": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 13270 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 | 1 | 2143 | 13270 | minor |
| 898 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } } |
blob | Long method, Feature envy | t | f | f | Long method, Feature envy | blob | 0 | 8150 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 | 2 | 898 | 8150 | minor |
| 206 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TruffleNFI_DLL implements DLLRFFI { public static final class NFIHandle implements LibHandle { @SuppressWarnings("unused") private final String libName; final TruffleObject libHandle; NFIHandle(String libName, TruffleObject libHandle) { this.libName = libName; this.libHandle = libHandle; } @Override public Type getRFFIType() { return RFFIFactory.Type.NFI; } } private static final class TruffleNFI_DLOpenNode extends Node implements DLLRFFI.DLOpenNode { @Override @TruffleBoundary public LibHandle execute(String path, boolean local, boolean now) { String librffiPath = LibPaths.getBuiltinLibPath("R"); // Do not call before/afterDowncall when loading libR to prevent the pushing/popping of // the callback array, which requires that the libR have already been loaded boolean notifyStateRFFI = !librffiPath.equals(path); long before = notifyStateRFFI ? RContext.getInstance().getStateRFFI().beforeDowncall(RFFIFactory.Type.NFI) : 0; try { String libName = DLL.libName(path); Env env = RContext.getInstance().getEnv(); TruffleObject libHandle = (TruffleObject) env.parse(Source.newBuilder("nfi", prepareLibraryOpen(path, local, now), path).build()).call(); return new NFIHandle(libName, libHandle); } finally { if (notifyStateRFFI) { RContext.getInstance().getStateRFFI().afterDowncall(before, RFFIFactory.Type.NFI); } } } } @TruffleBoundary private static String prepareLibraryOpen(String path, boolean local, boolean now) { StringBuilder sb = new StringBuilder("load"); sb.append("("); sb.append(local ? "RTLD_LOCAL" : "RTLD_GLOBAL"); sb.append('|'); sb.append(now ? "RTLD_NOW" : "RTLD_LAZY"); sb.append(") \""); sb.append(path); sb.append('"'); return sb.toString(); } private static class TruffleNFI_DLSymNode extends Node implements DLLRFFI.DLSymNode { @Child private Node lookupSymbol; @Override @TruffleBoundary public SymbolHandle execute(Object handle, String symbol) { assert handle instanceof NFIHandle; NFIHandle nfiHandle = (NFIHandle) handle; if (lookupSymbol == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); lookupSymbol = insert(Message.READ.createNode()); } try { TruffleObject result = (TruffleObject) ForeignAccess.sendRead(lookupSymbol, nfiHandle.libHandle, symbol); return new SymbolHandle(result); } catch (UnknownIdentifierException e) { throw new UnsatisfiedLinkError(); } catch (InteropException e) { throw RInternalError.shouldNotReachHere(); } } } private static class TruffleNFI_DLCloseNode extends Node implements DLLRFFI.DLCloseNode { @Override public int execute(Object handle) { assert handle instanceof NFIHandle; // TODO return 0; } } @Override public DLOpenNode createDLOpenNode() { return new TruffleNFI_DLOpenNode(); } @Override public DLSymNode createDLSymNode() { return new TruffleNFI_DLSymNode(); } @Override public DLCloseNode createDLCloseNode() { return new TruffleNFI_DLCloseNode(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2304 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.ffi.impl/src/com/oracle/truffle/r/ffi/impl/nfi/TruffleNFI_DLL.java/#L44-L145 | 2 | 206 | 2304 | minor |
| 1536 | YES, I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 11219 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 1536 | 11219 | minor |
| 2145 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 13274 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 1 | 2145 | 13274 | minor |
| 2374 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 14314 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 2374 | 14314 | major |
| 1863 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method (renderStats()) 3. Data class (BoltExecutorStats) 4. Magic number (numStatBuckets, this.rate) 5. Dead code (renderStats() method has no actual implementation) 6. Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies()) 7. Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions) 8. Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods) 9. Inappropriate comments (comment just stating "common stats" in renderStats() method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | Feature envy2 Long method (renderStats())3 Data class (BoltExecutorStats)4 Magic number (numStatBuckets, thisrate)5 Dead code (renderStats() method has no actual implementation)6 Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies())7 Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions)8 Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods)9 Inappropriate comments (comment just stating "common stats" in renderStats() method) | t | f | f | . Feature envy2. Long method (renderStats())3. Data class (BoltExecutorStats)4. Magic number (numStatBuckets, this.rate)5. Dead code (renderStats() method has no actual implementation)6. Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies())7. Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions)8. Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods)9. Inappropriate comments (comment just stating "common stats" in renderStats() method) | blob | 0 | 12226 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 1863 | 12226 | minor |
| 1540 | {"response":"YES I found bad smells","detected_bad_smells":["Long Method","Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class MonoWhen extends Mono implements SourceProducer { final boolean delayError; final Publisher[] sources; final Iterable> sourcesIterable; MonoWhen(boolean delayError, Publisher... sources) { this.delayError = delayError; this.sources = Objects.requireNonNull(sources, "sources"); this.sourcesIterable = null; } MonoWhen(boolean delayError, Iterable> sourcesIterable) { this.delayError = delayError; this.sources = null; this.sourcesIterable = Objects.requireNonNull(sourcesIterable, "sourcesIterable"); } @SuppressWarnings("unchecked") @Nullable Mono whenAdditionalSource(Publisher source) { Publisher[] oldSources = sources; if (oldSources != null) { int oldLen = oldSources.length; Publisher[] newSources = new Publisher[oldLen + 1]; System.arraycopy(oldSources, 0, newSources, 0, oldLen); newSources[oldLen] = source; return new MonoWhen(delayError, newSources); } return null; } @SuppressWarnings("unchecked") @Override public void subscribe(CoreSubscriber actual) { Publisher[] a; int n = 0; if (sources != null) { a = sources; n = a.length; } else { a = new Publisher[8]; for (Publisher m : sourcesIterable) { if (n == a.length) { Publisher[] b = new Publisher[n + (n >> 2)]; System.arraycopy(a, 0, b, 0, n); a = b; } a[n++] = m; } } if (n == 0) { Operators.complete(actual); return; } WhenCoordinator parent = new WhenCoordinator(actual, n, delayError); actual.onSubscribe(parent); parent.subscribe(a); } @Override public Object scanUnsafe(Attr key) { if (key == Attr.DELAY_ERROR) return delayError; return null; } static final class WhenCoordinator extends Operators.MonoSubscriber { final WhenInner[] subscribers; final boolean delayError; volatile int done; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater DONE = AtomicIntegerFieldUpdater.newUpdater(WhenCoordinator.class, "done"); @SuppressWarnings("unchecked") WhenCoordinator(CoreSubscriber subscriber, int n, boolean delayError) { super(subscriber); this.delayError = delayError; subscribers = new WhenInner[n]; for (int i = 0; i < n; i++) { subscribers[i] = new WhenInner(this); } } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.TERMINATED) { return done == subscribers.length; } if (key == Attr.BUFFERED) { return subscribers.length; } if (key == Attr.DELAY_ERROR) { return delayError; } return super.scanUnsafe(key); } @Override public Stream inners() { return Stream.of(subscribers); } void subscribe(Publisher[] sources) { WhenInner[] a = subscribers; for (int i = 0; i < a.length; i++) { sources[i].subscribe(a[i]); } } void signalError(Throwable t) { if (delayError) { signal(); } else { int n = subscribers.length; if (DONE.getAndSet(this, n) != n) { cancel(); actual.onError(t); } } } @SuppressWarnings("unchecked") void signal() { WhenInner[] a = subscribers; int n = a.length; if (DONE.incrementAndGet(this) != n) { return; } Throwable error = null; Throwable compositeError = null; for (int i = 0; i < a.length; i++) { WhenInner m = a[i]; Throwable e = m.error; if (e != null) { if (compositeError != null) { //this is ok as the composite created below is never a singleton compositeError.addSuppressed(e); } else if (error != null) { compositeError = Exceptions.multiple(error, e); } else { error = e; } } } if (compositeError != null) { actual.onError(compositeError); } else if (error != null) { actual.onError(error); } else { actual.onComplete(); } } @Override public void cancel() { if (!isCancelled()) { super.cancel(); for (WhenInner ms : subscribers) { ms.cancel(); } } } } static final class WhenInner implements InnerConsumer { final WhenCoordinator parent; volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater S = AtomicReferenceFieldUpdater.newUpdater(WhenInner.class, Subscription.class, "s"); Throwable error; WhenInner(WhenCoordinator parent) { this.parent = parent; } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.CANCELLED) { return s == Operators.cancelledSubscription(); } if (key == Attr.PARENT) { return s; } if (key == Attr.ACTUAL) { return parent; } if (key == Attr.ERROR) { return error; } return null; } @Override public Context currentContext() { return parent.currentContext(); } @Override public void onSubscribe(Subscription s) { if (Operators.setOnce(S, this, s)) { s.request(Long.MAX_VALUE); } else { s.cancel(); } } @Override public void onNext(Object t) { } @Override public void onError(Throwable t) { error = t; parent.signalError(t); } @Override public void onComplete() { parent.signal(); } void cancel() { Operators.terminate(S, this); } } } |
blob | Long Method, Feature Envy | t | f | f | Long Method, Feature Envy | blob | 0 | 11230 | https://github.com/reactor/reactor-core/blob/3958e2fabf49e16229dda5df39e7cde46797ec51/reactor-core/src/main/java/reactor/core/publisher/MonoWhen.java/#L36-L292 | 1 | 1540 | 11230 | major |
| 148 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1844 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 148 | 1844 | major |
| 4823 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 13121 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 1 | 4823 | 13121 | minor | ||
| 1098 | { "message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 9825 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 1098 | 9825 | major |
| 2010 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LayoutContext { /** * An {@link LayoutContext} notifies registered listeners about changes to * the layout algorithm using this property name. */ public static final String LAYOUT_ALGORITHM_PROPERTY = "layoutAlgorithm"; private ObjectProperty layoutAlgorithmProperty = new SimpleObjectProperty<>( this, LAYOUT_ALGORITHM_PROPERTY); private Graph graph; private final List postLayoutPass = new ArrayList<>(); private final List preLayoutPass = new ArrayList<>(); private final List layoutFilters = new ArrayList<>(); /** * Adds the given ILayoutFilter to this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to add to this context. */ public void addLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.add(layoutFilter); } /** * Applies the layout algorithm of this LayoutContext. The clean flag is * passed-in to the layout algorithm to indicate whether the context changed * significantly since the last layout pass. * * @param clear * true to indicate that the algorithm has to fully * re-compute the layout, otherwise false. */ public void applyLayout(boolean clear) { ILayoutAlgorithm layoutAlgorithm = layoutAlgorithmProperty.get(); if (layoutAlgorithm != null) { preLayout(); layoutAlgorithm.applyLayout(this, clear); postLayout(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run after the layout pass. Should not be * called by clients. */ public void postLayout() { for (Runnable r : new ArrayList<>(postLayoutPass)) { r.run(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run before the layout pass. Should not be * called by clients. */ public void preLayout() { for (Runnable r : preLayoutPass) { r.run(); } } /** * Returns the graph that is to be layouted. * * @return The {@link Graph} that is to be layouted. */ public Graph getGraph() { return graph; } /** * Sets the graph that is to be layouted by this context. * * @param graph * The {@link Graph} to layout. */ public void setGraph(Graph graph) { // TODO: we should not allow to pass in null here. Instead we should // guard ourselves against null. if (graph == null) { graph = new Graph(); } this.graph = graph; } /** * Returns all the nodes that should be laid out. Replacing elements in the * returned array does not affect this context. * * @return array of nodes to lay out */ // TODO: remove this (algorithms should use getGraph().getNodes()) public Node[] getNodes() { ObservableList nodes = graph.getNodes(); List layoutRelevantNodes = new ArrayList<>(); for (Node n : nodes) { if (!isLayoutIrrelevant(n)) { layoutRelevantNodes.add(n); } } return layoutRelevantNodes.toArray(new Node[] {}); } /** * Returns all the connections between nodes that should be laid out. * Replacing elements in the returned array does not affect this context. * * @return array of connections between nodes */ public Edge[] getEdges() { ObservableList edges = graph.getEdges(); List layoutRelevantEdges = new ArrayList<>(); for (Edge e : edges) { if (!isLayoutIrrelevant(e)) { layoutRelevantEdges.add(e); } } return layoutRelevantEdges.toArray(new Edge[] {}); } /** * Returns the static layout algorithm used to layout a newly initialized * graph or after heavy changes to it. * * @return The layout algorithm that is used by this {@link LayoutContext}. */ public ILayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithmProperty.get(); } /** * Returns true when the given {@link Edge} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param edge * The {@link Edge} in question. * @return true when the given {@link Edge} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Edge edge) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(edge)) { return true; } } return false; } /** * Returns true when the given {@link Node} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param nodeLayout * The {@link Node} in question. * @return true when the given {@link Node} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Node nodeLayout) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(nodeLayout)) { return true; } } return false; } /** * A property representing the layout algorithm used by this * {@link LayoutContext}. * * @see #getLayoutAlgorithm() * @see #setLayoutAlgorithm(ILayoutAlgorithm) * * @return A property named {@link #LAYOUT_ALGORITHM_PROPERTY}. */ public ObjectProperty layoutAlgorithmProperty() { return layoutAlgorithmProperty; }; /** * Removes the given ILayoutFilter from this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to remove to this context. */ public void removeLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.remove(layoutFilter); } /** * Adds the given {@link Runnable} to the list of runnables which are called * when this {@link LayoutContext} is asked to apply all changes made to its * elements to the display. * * @param runnable * A {@link Runnable} called whenever this context is asked to * apply all changes made to its elements to the display. */ public void schedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!postLayoutPass.contains(runnable)) { postLayoutPass.add(runnable); } } /** * Adds the given {@link Runnable} to the list of {@link Runnable}s which * are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to add to the list of {@link Runnable}s * which are executed before applying a layout. */ public void schedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!preLayoutPass.contains(runnable)) { preLayoutPass.add(runnable); } } /** * Sets the layout algorithm for this context. * * @param algorithm * The new {@link ILayoutAlgorithm} for this * {@link LayoutContext}. */ public void setLayoutAlgorithm(ILayoutAlgorithm algorithm) { layoutAlgorithmProperty.set(algorithm); } /** * Removes the given {@link Runnable} from the list of runnables which are * called when this {@link LayoutContext} is asked to apply all changes made * to its elements to the display. * * @param runnable * The {@link Runnable} that should no longer get called when * flushing changes. */ public void unschedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (postLayoutPass.contains(runnable)) { postLayoutPass.remove(runnable); } } /** * Removes the given {@link Runnable} from the list of {@link Runnable}s * which are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to remove from the list of * {@link Runnable}s which are executed before applying a layout. */ public void unschedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (preLayoutPass.contains(runnable)) { preLayoutPass.remove(runnable); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12748 | https://github.com/eclipse/gef/blob/8f2649b90ab14a1bb010188036d4eedf7586e123/org.eclipse.gef.layout/src/org/eclipse/gef/layout/LayoutContext.java/#L35-L315 | 1 | 2010 | 12748 | major |
| 95 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 2 | 95 | 1268 | minor |
| 565 | YES I found bad smells the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method. 2. Feature envy. | data class | 0 | 5717 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 2 | 565 | 5717 | minor |
| 3814 | {"error": "Sorry, I cannot provide code analysis or detect code smells. However, I can offer guidance or information on how to identify and address common code smells in Java code."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ClasspathUriUtil { public static final String CLASSPATH_SCHEME = "classpath"; public static boolean isClasspathUri(URI uri) { if (uri == null) return false; String scheme = uri.scheme(); return CLASSPATH_SCHEME.equals(scheme); } } |
data class | f | f | f | data class | 0 | 9713 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/resource/ClasspathUriUtil.java/#L20-L31 | 1 | 3814 | 9713 | minor | ||
| 241 | { "output": "YES I found bad smells", "the bad smells are": [ "Long method", "Duplicate code", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | long method, duplicate code, feature envy | t | t | f | long method, duplicate code, feature envy | data class | 0 | 2643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 241 | 2643 | minor |
| 1988 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12677 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 1 | 1988 | 12677 | minor |
| 2662 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | long method | t | t | f | long method | data class | 0 | 15197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2662 | 15197 | minor |
| 2347 | YES I found bad smells the bad smells are: 1. Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class. 2. Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified. 3. Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable. 4. Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes. 5. Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend. 6. Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication. 7. Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away. 8. Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field. 9. Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class. 10. Lack of Encapsulation - The class exposes all of its fields publicly, which could lead to unwanted modifications or misuse. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class2 Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified3 Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable4 Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes5 Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend6 Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication7 Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away8 Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field9 Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class | t | f | f | . Feature Envy - The class is heavily dependent on external classes such as Primitives, ParameterizedType, and Class.2. Long Method - The constructor and the analyzeParametrizedType methods are quite lengthy and could potentially be simplified.3. Inconsistent Naming - Some variable names are in camelCase while others are in snake_case, making the code less readable.4. Low Cohesion - The class has multiple responsibilities, such as converting types and analyzing them, which could be split into separate classes.5. Inappropriate Intimacy - The class is tightly coupled with external classes, making it difficult to modify or extend.6. Shotgun Surgery - Any changes to external classes or the structure of the constructor could require changes to this class as well, leading to code duplication.7. Incomplete Abstraction - The class directly accesses and uses the fields and methods of external classes, instead of abstracting them away.8. Primitive Obsession - The class has multiple boolean fields to represent different types, which could be abstracted into one single Enum field.9. Data Clumps - The class uses multiple related fields to represent the type and subtype relationship, which could be better represented as a single field or class. | data class | 0 | 14196 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 2347 | 14196 | major |
| 1427 | { "error": "Unable to provide a valid JSON response. Please make sure to input a Java code snippet." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | Not specified | f | f | f | false | 0 | 10945 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 1 | 1427 | 10945 | minor | |
| 265 | {"response":"YES I found bad smells","bad smells are":["1. Long Method","2. Feature Envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2876 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 2 | 265 | 2876 | major |
| 737 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. */ @Parameter( property = "project.build.directory", required = true ) protected File targetDirectory; /** * The output directory for the final HTML report. Note that this parameter is only evaluated if the goal is run * directly from the command line or during the default lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is used instead. */ @Parameter( property = "project.reporting.outputDirectory", required = true ) protected File outputDirectory; /** * Site rendering component for generating the HTML report. */ @Component private Renderer siteRenderer; /** * The project to analyse. */ @Parameter( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available * renderers. XML is required if the pmd:check goal is being used. */ @Parameter( property = "format", defaultValue = "xml" ) protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ @Parameter( property = "linkXRef", defaultValue = "true" ) private boolean linkXRef; /** * Location of the Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) private File xrefLocation; /** * Location of the Test Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these * exclusion patterns only operate on the path of a source file relative to its source root directory. In other * words, files are excluded based on their package and/or class name. If you want to exclude entire source root * directories, use the parameter excludeRoots instead. * * @since 2.2 */ @Parameter private List excludes; /** * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to * **\/*.java. * * @since 2.2 */ @Parameter private List includes; /** * Specifies the location of the source directories to be used for PMD. * Defaults to project.compileSourceRoots. * @since 3.7 */ @Parameter( defaultValue = "${project.compileSourceRoots}" ) private List compileSourceRoots; /** * The directories containing the test-sources to be used for PMD. * Defaults to project.testCompileSourceRoots * @since 3.7 */ @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 */ @Parameter private File[] excludeRoots; /** * Run PMD on the tests. * * @since 2.2 */ @Parameter( defaultValue = "false" ) protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @since 2.2 */ @Parameter( property = "aggregate", defaultValue = "false" ) protected boolean aggregate; /** * The file encoding to use when reading the Java sources. * * @since 2.3 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String sourceEncoding; /** * The file encoding when writing non-HTML reports. * * @since 2.5 */ @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) private String outputEncoding; /** * The projects in the reactor for aggregation report. */ @Parameter( property = "reactorProjects", readonly = true ) protected List reactorProjects; /** * Whether to include the xml files generated by PMD/CPD in the site. * * @since 3.0 */ @Parameter( defaultValue = "false" ) protected boolean includeXmlInSite; /** * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to * true. * * @since 3.1 */ @Parameter( defaultValue = "true" ) protected boolean skipEmptyReport; /** * File that lists classes and rules to be excluded from failures. * For PMD, this is a properties file. For CPD, this * is a text file that contains comma-separated lists of classes * that are allowed to duplicate. * * @since 3.7 */ @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) protected String excludeFromFailureFile; /** The files that are being analyzed. */ protected Map filesToProcess; /** * {@inheritDoc} */ @Override protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ @Override protected Renderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way @SuppressWarnings( "unchecked" ) List reportPlugins = project.getReportPlugins(); for ( ReportPlugin plugin : reportPlugins ) { String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ protected Map getFilesToProcess() throws IOException { if ( aggregate && !project.isExecutionRoot() ) { return Collections.emptyMap(); } if ( excludeRoots == null ) { excludeRoots = new File[0]; } Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); for ( File file : excludeRoots ) { if ( file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList<>(); if ( null == compileSourceRoots ) { compileSourceRoots = project.getCompileSourceRoots(); } if ( compileSourceRoots != null ) { for ( String root : compileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } } } if ( null == testSourceRoots ) { testSourceRoots = project.getTestCompileSourceRoots(); } if ( includeTests ) { if ( testSourceRoots != null ) { for ( String root : testSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } } } if ( aggregate ) { for ( MavenProject localProject : reactorProjects ) { @SuppressWarnings( "unchecked" ) List localCompileSourceRoots = localProject.getCompileSourceRoots(); for ( String root : localCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } } if ( includeTests ) { @SuppressWarnings( "unchecked" ) List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); for ( String root : localTestCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } } String excluding = getExcludes(); getLog().debug( "Exclusions: " + excluding ); String including = getIncludes(); getLog().debug( "Inclusions: " + including ); Map files = new TreeMap<>(); for ( PmdFileInfo finfo : directories ) { getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); for ( File newfile : newfiles ) { files.put( newfile.getCanonicalFile(), finfo ); } } } return files; } private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) { boolean returnVal = false; for ( File excludeDir : excludeRootFiles ) { try { if ( sourceDirectoryToCheck.getCanonicalPath().startsWith( excludeDir.getCanonicalPath() ) ) { getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() + " has been excluded as it matches excludeRoot " + excludeDir.getAbsolutePath() ); returnVal = true; break; } } catch ( IOException e ) { getLog().warn( "Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e ); } } return returnVal; } /** * Gets the comma separated list of effective include patterns. * * @return The comma separated list of effective include patterns, never null. */ private String getIncludes() { Collection patterns = new LinkedHashSet<>(); if ( includes != null ) { patterns.addAll( includes ); } if ( patterns.isEmpty() ) { patterns.add( "**/*.java" ); } return StringUtils.join( patterns.iterator(), "," ); } /** * Gets the comma separated list of effective exclude patterns. * * @return The comma separated list of effective exclude patterns, never null. */ private String getExcludes() { Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); if ( excludes != null ) { patterns.addAll( excludes ); } return StringUtils.join( patterns.iterator(), "," ); } protected boolean isHtml() { return "html".equals( format ); } protected boolean isXml() { return "xml".equals( format ); } /** * {@inheritDoc} */ @Override public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } if ( "pom".equals( project.getPackaging() ) && !aggregate ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( isXml() ) { return true; } try { filesToProcess = getFilesToProcess(); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * {@inheritDoc} */ @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } protected String getSourceEncoding() { return sourceEncoding; } /** * Gets the effective reporting output files encoding. * * @return The effective reporting output file encoding, never null. * @since 2.5 */ protected String getOutputEncoding() { return ( outputEncoding != null ) ? outputEncoding : ReaderFactory.UTF_8; } static String getPmdVersion() { try { return (String) PMD.class.getField( "VERSION" ).get( null ); } catch ( IllegalAccessException e ) { throw new RuntimeException( "PMD VERSION field not accessible", e ); } catch ( NoSuchFieldException e ) { throw new RuntimeException( "PMD VERSION field not found", e ); } } } |
blob | long method | t | t | f | long method | blob | 0 | 6935 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-pmd-plugin/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java/#L52-L553 | 1 | 737 | 6935 | critical |
| 1697 | YES I found bad smells the bad smells are: 1. Too many nested static classes, leading to complexity and potential confusion. 2. Use of a try-catch block with generic exception handling, making it difficult to handle specific exceptions and leading to potential runtime errors. 3. Lack of encapsulation and abstraction, with direct access to fields and methods in other classes. 4. Use of hardcoded values, such as class names and constants, which could make the code less flexible and maintainable. 5. Potential for duplicate code, as the compareTo methods in the PureJavaComparer and UnsafeComparer classes have a lot of similar code. 6. Potential for unclear responsibilities and a violation of single responsibility principle, as the classes have multiple functionalities and handle both comparisons and buffer operations. 7. Use of bitwise operations for comparisons, which could be less efficient and more error-prone than using built-in comparison methods. 8. Potential for unsafe code, as indicated by the class name and the use of the "unsafe" method in the UnsafeComparer class. 9. Use of if statements to check for a specific error, instead of using an appropriate exception handling approach. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
blob | Too many nested static classes, leading to complexity and potential confusion2 Use of a try-catch block with generic exception handling, making it difficult to handle specific exceptions and leading to potential runtime errors 3 Lack of encapsulation and abstraction, with direct access to fields and methods in other classes 4 Use of hardcoded values, such as class names and constants, which could make the code less flexible and maintainable5 Potential for duplicate code, as the compareTo methods in the PureJavaComparer and UnsafeComparer classes have a lot of similar code 6 Potential for unclear responsibilities and a violation of single responsibility principle, as the classes have multiple functionalities and handle both comparisons and buffer operations 7 Use of bitwise operations for comparisons, which could be less efficient and more error-prone than using built-in comparison methods 8 Potential for unsafe code, as indicated by the class name and the use of the "unsafe" method in the UnsafeComparer class 9 Use of if statements to check for a specific error, instead of using an appropriate exception handling approach | t | f | f | . Too many nested static classes, leading to complexity and potential confusion.2. Use of a try-catch block with generic exception handling, making it difficult to handle specific exceptions and leading to potential runtime errors. 3. Lack of encapsulation and abstraction, with direct access to fields and methods in other classes. 4. Use of hardcoded values, such as class names and constants, which could make the code less flexible and maintainable.5. Potential for duplicate code, as the compareTo methods in the PureJavaComparer and UnsafeComparer classes have a lot of similar code. 6. Potential for unclear responsibilities and a violation of single responsibility principle, as the classes have multiple functionalities and handle both comparisons and buffer operations. 7. Use of bitwise operations for comparisons, which could be less efficient and more error-prone than using built-in comparison methods. 8. Potential for unsafe code, as indicated by the class name and the use of the "unsafe" method in the UnsafeComparer class. 9. Use of if statements to check for a specific error, instead of using an appropriate exception handling approach. | blob | 0 | 11729 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 2 | 1697 | 11729 | minor |
| 218 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HDFSTextLineReader { private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; private int bufferSize = DEFAULT_BUFFER_SIZE; private FSDataInputStream reader; private byte[] buffer; // the number of bytes of real data in the buffer private int bufferLength = 0; // the current position in the buffer private int bufferPosn = 0; private long currentFilePos = 0L; private static final byte CR = '\r'; private static final byte LF = '\n'; public static final String KEY_BUFFER_SIZE = "io.file.buffer.size"; /** * Create a line reader that reads from the given stream using the * default buffer-size (32k). * * @param in * The input stream * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in) throws IOException { this(in, DEFAULT_BUFFER_SIZE); } /** * Create a line reader that reads from the given stream using the * given buffer-size. * * @param in * The input stream * @param bufferSize * Size of the read buffer * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, int bufferSize) throws IOException { this.reader = in; this.bufferSize = bufferSize; this.buffer = new byte[this.bufferSize]; currentFilePos = in.getPos(); } public HDFSTextLineReader() throws IOException { this.bufferSize = DEFAULT_BUFFER_SIZE; this.buffer = new byte[this.bufferSize]; } /** * Create a line reader that reads from the given stream using the io.file.buffer.size specified in the given Configuration. * * @param in * input stream * @param conf * configuration * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, Configuration conf) throws IOException { this(in, conf.getInt(KEY_BUFFER_SIZE, DEFAULT_BUFFER_SIZE)); } /** * Read one line from the InputStream into the given Text. A line * can be terminated by one of the following: '\n' (LF) , '\r' (CR), * or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated * line. * * @param str * the object to store the given line (without newline) * @param maxLineLength * the maximum number of bytes to store into str; * the rest of the line is silently discarded. * @param maxBytesToConsume * the maximum number of bytes to consume * in this call. This is only a hint, because if the line cross * this threshold, we allow it to happen. It can overshoot * potentially by as much as one buffer length. * @return the number of bytes read including the (longest) newline * found. * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { /* We're reading data from in, but the head of the stream may be * already buffered in buffer, so we have several cases: * 1. No newline characters are in the buffer, so we need to copy * everything and read another buffer from the stream. * 2. An unambiguously terminated line is in buffer, so we just * copy to str. * 3. Ambiguously terminated line is in buffer, i.e. buffer ends * in CR. In this case we copy everything up to CR to str, but * we also need to see what follows CR: if it's LF, then we * need consume LF as well, so next call to readLine will read * from after that. * We use a flag prevCharCR to signal if previous character was CR * and, if it happens to be at the end of the buffer, delay * consuming it until we have a chance to look at the char that * follows. */ str.clear(); int txtLength = 0; //tracks str.getLength(), as an optimization int newlineLength = 0; //length of terminating newline boolean prevCharCR = false; //true of prev char was CR long bytesConsumed = 0; do { int startPosn = bufferPosn; //starting from where we left off the last time if (bufferPosn >= bufferLength) { startPosn = bufferPosn = 0; if (prevCharCR) ++bytesConsumed; //account for CR from previous read bufferLength = reader.read(buffer); if (bufferLength <= 0) break; // EOF } for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline if (buffer[bufferPosn] == LF) { newlineLength = (prevCharCR) ? 2 : 1; ++bufferPosn; // at next invocation proceed from following byte break; } if (prevCharCR) { //CR + notLF, we are at notLF newlineLength = 1; break; } prevCharCR = (buffer[bufferPosn] == CR); } int readLength = bufferPosn - startPosn; if (prevCharCR && newlineLength == 0) --readLength; //CR at the end of the buffer bytesConsumed += readLength; int appendLength = readLength - newlineLength; if (appendLength > maxLineLength - txtLength) { appendLength = maxLineLength - txtLength; } if (appendLength > 0) { str.append(buffer, startPosn, appendLength); txtLength += appendLength; } } while (newlineLength == 0 && bytesConsumed < maxBytesToConsume); if (bytesConsumed > Integer.MAX_VALUE) throw new IOException("Too many bytes before newline: " + bytesConsumed); currentFilePos = reader.getPos() - bufferLength + bufferPosn; return (int) bytesConsumed; } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @param maxLineLength * the maximum number of bytes to store into str. * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength) throws IOException { return readLine(str, maxLineLength, Integer.MAX_VALUE); } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str) throws IOException { return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE); } public void seek(long desired) throws IOException { if (reader.getPos() <= desired || currentFilePos > desired) { // desired position is ahead of stream or before the current position, seek to position reader.seek(desired); bufferLength = 0; bufferPosn = 0; currentFilePos = desired; } else if (currentFilePos < desired) { // desired position is in the buffer int difference = (int) (desired - currentFilePos); bufferPosn += difference; currentFilePos = desired; } } public FSDataInputStream getReader() { return reader; } public void resetReader(FSDataInputStream reader) throws IOException { this.reader = reader; bufferLength = 0; bufferPosn = 0; currentFilePos = reader.getPos(); } public void close() throws IOException { reader.close(); } } |
blob | Not specified | f | f | f | false | 0 | 2369 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/HDFSTextLineReader.java/#L27-L234 | 2 | 218 | 2369 | major | |
| 667 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 6549 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 2 | 667 | 6549 | minor |
| 39 | {"response": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | "YES I found bad smells", "bad smells are" | t | f | f | "YES I found bad smells", "bad smells are" | blob | 0 | 767 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 1 | 39 | 767 | critical |
| 2244 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Misleading variable names 3. Unnecessary comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Duplicate code2 Misleading variable names3 Unnecessary comments | t | f | f | . Duplicate code2. Misleading variable names3. Unnecessary comments | data class | 0 | 13631 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 2244 | 13631 | major |
| 2479 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14592 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 2 | 2479 | 14592 | major |
| 1684 | {"message": "YES I found bad smells", "bad smells are": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
blob | 2 Data Class | t | f | f | 2. Data Class | blob | 0 | 11684 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 1 | 1684 | 11684 | minor |
| 675 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6572 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 1 | 675 | 6572 | minor |
| 726 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6846 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 726 | 6846 | major |
| 2466 | { "response": "YES I found bad smells", "detected bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14563 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 2466 | 14563 | minor |
| 2285 | YES I found bad smells the bad smells are: 1.Long Method, 2.Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | Long Method, 2Feature Envy | t | f | f | .Long Method, 2.Feature Envy | data class | 0 | 13867 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 2285 | 13867 | minor |
| 154 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String repeat(String s, int c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c; i++) sb.append(s); return sb.toString(); } |
feature envy | long method, duplicate code | t | t | f | long method, duplicate code | feature envy | 0 | 1939 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/shell/src/main/java/org/apache/accumulo/shell/Shell.java/#L1075-L1080 | 2 | 154 | 1939 | minor |
| 200 | { "message": "YES, I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LogTransformer extends Transformer { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public Object transformRow(Map row, Context ctx) { String expr = ctx.getEntityAttribute(LOG_TEMPLATE); String level = ctx.replaceTokens(ctx.getEntityAttribute(LOG_LEVEL)); if (expr == null || level == null) return row; if ("info".equals(level)) { if (log.isInfoEnabled()) log.info(ctx.replaceTokens(expr)); } else if ("trace".equals(level)) { if (log.isTraceEnabled()) log.trace(ctx.replaceTokens(expr)); } else if ("warn".equals(level)) { if (log.isWarnEnabled()) log.warn(ctx.replaceTokens(expr)); } else if ("error".equals(level)) { if (log.isErrorEnabled()) log.error(ctx.replaceTokens(expr)); } else if ("debug".equals(level)) { if (log.isDebugEnabled()) log.debug(ctx.replaceTokens(expr)); } return row; } public static final String LOG_TEMPLATE = "logTemplate"; public static final String LOG_LEVEL = "logLevel"; } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2244 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/LogTransformer.java/#L35-L67 | 2 | 200 | 2244 | minor |
| 1391 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BucketList implements Iterable> { private final ArrayList> bucketList; private final List> immutableVisibleList; private BucketList(ArrayList> bucketList, ArrayList> publicBucketList) { this.bucketList = bucketList; int displayIndex = 0; for (Bucket bucket : publicBucketList) { bucket.displayIndex = displayIndex++; } immutableVisibleList = Collections.unmodifiableList(publicBucketList); } private int getBucketCount() { return immutableVisibleList.size(); } private int getBucketIndex(CharSequence name, Collator collatorPrimaryOnly) { // binary search int start = 0; int limit = bucketList.size(); while ((start + 1) < limit) { int i = (start + limit) / 2; Bucket bucket = bucketList.get(i); int nameVsBucket = collatorPrimaryOnly.compare(name, bucket.lowerBoundary); if (nameVsBucket < 0) { limit = i; } else { start = i; } } Bucket bucket = bucketList.get(start); if (bucket.displayBucket != null) { bucket = bucket.displayBucket; } return bucket.displayIndex; } /** * Private iterator over all the buckets, visible and invisible */ private Iterator> fullIterator() { return bucketList.iterator(); } /** * Iterator over just the visible buckets. */ @Override public Iterator> iterator() { return immutableVisibleList.iterator(); // use immutable list to prevent remove(). } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 10842 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/AlphabeticIndex.java/#L1101-L1154 | 2 | 1391 | 10842 | minor |
| 160 | { "response": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | Not specified | f | f | f | false | 0 | 1985 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 2 | 160 | 1985 | major | |
| 1557 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11288 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 2 | 1557 | 11288 | major |
| 629 | " YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 6279 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 2 | 629 | 6279 | critical |
| 2398 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2398 | 14376 | minor |
| 2321 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | Long methods2 Feature envy | t | f | f | . Long methods2. Feature envy | data class | 0 | 14130 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 2321 | 14130 | major |
| 931 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8355 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 2 | 931 | 8355 | minor |
| 420 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 4240 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 2 | 420 | 4240 | major |
| 16 | {"error": "Exceeded maximum character limit. Please shorten your request and try again."} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Not specified | f | f | f | false | 0 | 642 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 16 | 642 | major | |
| 2636 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Insufficient comments/documentation 6. Catch-all exception handling 7. Use of global variables/constants instead of local ones 8. Inconsistent naming conventions 9. Use of deprecated code 10. Lack of exception handling for potential errors/exceptions 11. Data conversion/comparison without proper error handling 12. Mixing of formatting styles (i.e. using both String.format and concatenation) 13. Overly complex/convoluted logic 14. Repeating code 15. Inadequate test coverage/missing test cases 16. Lack of use of standard libraries/utilities where appropriate. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Insufficient comments/documentation6 Catch-all exception handling7 Use of global variables/constants instead of local ones8 Inconsistent naming conventions9 Use of deprecated code | t | f | f | . Long method2. Feature envy3. Duplicate code4. Magic numbers5. Insufficient comments/documentation6. Catch-all exception handling7. Use of global variables/constants instead of local ones8. Inconsistent naming conventions9. Use of deprecated code | blob | 0 | 15118 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 2 | 2636 | 15118 | minor |
| 5399 | found. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 15171 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L233896-L233981 | 2 | 5399 | 15171 | minor | ||
| 810 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; } |
blob | data class | t | t | f | data class | blob | 0 | 7648 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 | 1 | 810 | 7648 | major |
| 956 | YES, I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 8539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 956 | 8539 | minor |
| 5782 | {"response": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 15318 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5782 | 15318 | minor |
| 2258 | YES, I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 13695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 2 | 2258 | 13695 | minor |
| 2224 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13570 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 2224 | 13570 | major |
| 670 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 6553 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 670 | 6553 | minor |
| 4573 | of the above No, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12153 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 2 | 4573 | 12153 | minor | ||
| 2152 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 13294 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 2152 | 13294 | minor |
| 1079 | { "answer": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } } |
blob | long method | t | t | f | long method | blob | 0 | 9655 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 | 1 | 1079 | 9655 | major |
| 864 | opens = new Open[count]; YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7920 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 864 | 7920 | minor |
| 358 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Exception handling, 4.Magic numbers, 5.Deeply nested code, 6.Code duplication, 7.Non-descriptive names, 8.Poor exception handling, 9.Inconsistent naming conventions, 10.Poor error handling approach | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SafeFileOutputStream extends FilterOutputStream { private final Path desiredFile; private Path tempFile; boolean desiredAlreadyExisted; public SafeFileOutputStream(Path file) throws IOException { this(file, tempFile(file)); } public SafeFileOutputStream(Path desiredFile, Path tempFile) throws IOException { super(Files.newOutputStream(tempFile)); this.desiredFile = desiredFile; this.tempFile = tempFile; // Some useful things to check that we preferably don't want to fail on // close() desiredAlreadyExisted = Files.exists(desiredFile); Path desiredFolder = this.desiredFile.getParent(); if (desiredAlreadyExisted) { if (!Files.isWritable(desiredFile)) { throw new FileNotFoundException("Can't write to " + desiredFile); } } else { if (!Files.exists(desiredFolder)) { throw new FileNotFoundException("Folder does not exist: " + desiredFolder); } if (!Files.isDirectory(desiredFolder)) { throw new FileNotFoundException("Not a directory: " + desiredFolder); } } if (!Files.isWritable(desiredFolder)) { throw new FileNotFoundException("Can't modify folder " + desiredFolder); } } private static Path tempFile(Path file) throws IOException { return Files.createTempFile(file.getParent(), file.getFileName() .toString(), ".tmp"); } @Override public void close() throws IOException { // If super.close fails - we leave the tempfiles behind super.close(); if (!Files.exists(tempFile)) { // Probably something went wrong before close called, // like rollback() return; } Path beforeDeletion = null; try { if (desiredAlreadyExisted) { // In case renaming goes wrong, we don't want to have already // deleted the // desired file. So we'll rename it to another temporary file // instead which // we can delete on successful rename. beforeDeletion = tempFile(desiredFile); if (!Files.deleteIfExists(beforeDeletion)) { // Should not happen, we just made it! throw new IOException("Can't delete temporary file " + beforeDeletion); } Files.move(desiredFile, beforeDeletion, StandardCopyOption.ATOMIC_MOVE); } try { Files.move(tempFile, desiredFile, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { // We'll leave our tempFiles for recovery. tempFile = null; beforeDeletion = null; if (Files.exists(desiredFile)) { // Someone else added or replaced the file afterwards, // kind-a OK return; } throw e; } } finally { if (beforeDeletion != null) { Files.deleteIfExists(beforeDeletion); } if (tempFile != null) { Files.deleteIfExists(tempFile); } } } public void rollback() throws IOException { super.close(); Files.deleteIfExists(tempFile); } } |
blob | Long method, 2Feature envy, 3Exception handling, 4Magic numbers, 5Deeply nested code, 6Code duplication, 7Non-descriptive names, 8Poor exception handling, 9Inconsistent naming conventions, | t | f | f | .Long method, 2.Feature envy, 3.Exception handling, 4.Magic numbers, 5.Deeply nested code, 6.Code duplication, 7.Non-descriptive names, 8.Poor exception handling, 9.Inconsistent naming conventions, | blob | 0 | 3683 | https://github.com/apache/incubator-taverna-engine/blob/98536c6b702a0541debbb66be996455384561b54/taverna-prov/src/main/java/org/apache/taverna/prov/SafeFileOutputStream.java/#L36-L137 | 2 | 358 | 3683 | minor |
| 2022 | 1. Long method 2. Data class 3. Large class 4. Primitive obsession 5. Duplicated code 6. Feature envy 7. Inconsistent naming convention 8. Inappropriate comment | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } } |
blob | Long method2 Data class3 Large class4 Primitive obsession5 Duplicated code6 Feature envy7 Inconsistent naming convention8 Inappropriate comment | f | f | f | . Long method2. Data class3. Large class4. Primitive obsession5. Duplicated code6. Feature envy7. Inconsistent naming convention8. Inappropriate comment | blob | 0 | 12792 | https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 | 2 | 2022 | 12792 | minor |
| 125 | { "response": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1573 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 125 | 1573 | critical |
| 1765 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11903 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 2 | 1765 | 11903 | minor |
| 5028 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13962 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 5028 | 13962 | major |
| 1054 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { // @formatter:off @Override protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages .simpMessageDestMatchers("/queue/**", "/topic/**").denyAll() .simpSubscribeDestMatchers("/queue/**/*-user*", "/topic/**/*-user*").denyAll() .anyMessage().authenticated(); } // @formatter:on } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 9489 | https://github.com/spring-projects/spring-session/blob/a5a3bc5d0b57d396882199dfbf8cb560a355ca1e/samples/boot/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java/#L26-L39 | 1 | 1054 | 9489 | minor |
| 283 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Switch statement 5. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private final class SymbolProcessor implements FunctionVisitor, InstructionVisitorAdapter { private final SourceFunction function; private final LinkedList removeFromBlock = new LinkedList<>(); private int blockInstIndex = 0; private DbgValueInstruction lastDbgValue = null; private InstructionBlock currentBlock = null; private SymbolProcessor(SourceFunction function) { this.function = function; } @Override public void visit(InstructionBlock block) { currentBlock = block; lastDbgValue = null; for (blockInstIndex = 0; blockInstIndex < block.getInstructionCount(); blockInstIndex++) { block.getInstruction(blockInstIndex).accept(this); } if (!removeFromBlock.isEmpty()) { for (int i : removeFromBlock) { currentBlock.remove(i); } removeFromBlock.clear(); } } @Override public void visitInstruction(Instruction instruction) { final MDLocation loc = instruction.getDebugLocation(); if (loc != null) { final LLVMSourceLocation scope = cache.buildLocation(loc); if (scope != null) { instruction.setSourceLocation(scope); } } } @Override public void visit(VoidCallInstruction call) { final SymbolImpl callTarget = call.getCallTarget(); if (callTarget instanceof FunctionDeclaration) { switch (((FunctionDeclaration) callTarget).getName()) { case LLVM_DBG_DECLARE_NAME: handleDebugIntrinsic(call, true); return; case LLVM_DBG_ADDR_NAME: // dbg.declare and dbg.addr have the same interface and, for our purposes, // the same semantics handleDebugIntrinsic(call, true); return; case LLVM_DBG_VALUE_NAME: handleDebugIntrinsic(call, false); return; case LLVM_DEBUGTRAP_NAME: visitDebugTrap(call); return; } } visitInstruction(call); } private void visitDebugTrap(VoidCallInstruction call) { final DebugTrapInstruction trap = DebugTrapInstruction.create(call); currentBlock.set(blockInstIndex, trap); visitInstruction(trap); } private SourceVariable getVariable(VoidCallInstruction call, int index) { final SymbolImpl varSymbol = getArg(call, index); if (varSymbol instanceof MetadataSymbol) { final MDBaseNode mdLocal = ((MetadataSymbol) varSymbol).getNode(); final LLVMSourceSymbol symbol = cache.getSourceSymbol(mdLocal, false); return function.getLocal(symbol); } return null; } private void handleDebugIntrinsic(VoidCallInstruction call, boolean isDeclaration) { SymbolImpl value = getArg(call, LLVM_DBG_INTRINSICS_VALUE_ARGINDEX); if (value instanceof MetadataSymbol) { value = MDSymbolExtractor.getSymbol(((MetadataSymbol) value).getNode()); } if (value == null) { // this may happen if llvm optimizations removed a variable value = new NullConstant(MetaType.DEBUG); } else if (value instanceof ValueInstruction) { ((ValueInstruction) value).setSourceVariable(true); } else if (value instanceof FunctionParameter) { ((FunctionParameter) value).setSourceVariable(true); } int mdLocalArgIndex; int mdExprArgIndex; if (isDeclaration) { mdLocalArgIndex = LLVM_DBG_DECLARE_LOCALREF_ARGINDEX; mdExprArgIndex = LLVM_DBG_DECLARE_EXPR_ARGINDEX; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_NEW) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_NEW; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_NEW; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_OLD; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_OLD; } else { return; } final SourceVariable variable = getVariable(call, mdLocalArgIndex); if (variable == null) { // invalid or unsupported debug information // remove upper indices so we do not need to update the later ones removeFromBlock.addFirst(blockInstIndex); return; } final MDExpression expression = getExpression(call, mdExprArgIndex); if (ValueFragment.describesFragment(expression)) { variable.addFragment(ValueFragment.parse(expression)); } else { variable.addFullDefinition(); } if (isDeclaration) { final DbgDeclareInstruction dbgDeclare = new DbgDeclareInstruction(value, variable, expression); variable.addDeclaration(dbgDeclare); currentBlock.set(blockInstIndex, dbgDeclare); } else { long index = 0; if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { final SymbolImpl indexSymbol = call.getArgument(LLVM_DBG_VALUE_INDEX_ARGINDEX_OLD); final Long l = LLVMSymbolReadResolver.evaluateLongIntegerConstant(indexSymbol); if (l != null) { index = l; } } final DbgValueInstruction dbgValue = new DbgValueInstruction(value, variable, index, expression); if (dbgValue.equals(lastDbgValue)) { // at higher optimization levels llvm often duplicates the @llvm.dbg.value // intrinsic call, we remove it again to avoid unnecessary runtime overhead removeFromBlock.addFirst(blockInstIndex); } else { variable.addValue(dbgValue); currentBlock.set(blockInstIndex, dbgValue); lastDbgValue = dbgValue; } } } } |
blob | Long method2 Feature envy3 Duplicate code4 Switch statement5 Data class | t | f | f | . Long method2. Feature envy3. Duplicate code4. Switch statement5. Data class | blob | 0 | 3035 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/sulong/projects/com.oracle.truffle.llvm.parser/src/com/oracle/truffle/llvm/parser/metadata/debuginfo/DebugInfoFunctionProcessor.java/#L145-L308 | 2 | 283 | 3035 | critical |
| 204 | {"response": "YES I found bad smells", "the bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static final class XdrInputFormat extends PInputStream { private static final int READ_BUFFER_SIZE = 32 * 1024; private final class Buffer { private final byte[] buf; private int size; private int offset; Buffer(byte[] buf) { this.buf = buf; } int readInt() { return ((buf[offset++] & 0xff) << 24 | (buf[offset++] & 0xff) << 16 | (buf[offset++] & 0xff) << 8 | (buf[offset++] & 0xff)); } double readDouble() { long val = ((long) (buf[offset++] & 0xff) << 56 | (long) (buf[offset++] & 0xff) << 48 | (long) (buf[offset++] & 0xff) << 40 | (long) (buf[offset++] & 0xff) << 32 | (long) (buf[offset++] & 0xff) << 24 | (long) (buf[offset++] & 0xff) << 16 | (long) (buf[offset++] & 0xff) << 8 | buf[offset++] & 0xff); return Double.longBitsToDouble(val); } @SuppressWarnings("deprecation") String readString(int len) { /* * This fast path uses a cheaper String constructor if all incoming bytes are in the * 0-127 range. */ boolean fastEncode = true; for (int i = 0; i < len; i++) { byte b = buf[offset + i]; if (b < 0) { fastEncode = false; break; } } String result; if (fastEncode) { result = new String(buf, 0, offset, len); } else { result = new String(buf, offset, len, StandardCharsets.UTF_8); } offset += len; WeakReference entry; if ((entry = strings.get(result)) != null) { String string = entry.get(); if (string != null) { return string; } } strings.put(result, new WeakReference<>(result)); return result; } void readRaw(byte[] data) { System.arraycopy(buf, offset, data, 0, data.length); offset += data.length; } void readData(int n) throws IOException { if (offset + n > size) { if (offset != size) { // copy end piece to beginning System.arraycopy(buf, offset, buf, 0, size - offset); } size -= offset; offset = 0; while (size < n) { // read some more data int nread = is.read(buf, size, buf.length - size); if (nread <= 0) { throw RInternalError.unimplemented("handle unexpected eof"); } size += nread; } } } } /** * This buffer is used under normal circumstances, i.e. when the read data blocks are * smaller than the initial buffer. The ensureData method creates a special buffer for * reading big chunks of data exceeding the default buffer. */ private final Buffer defaultBuffer; private final WeakHashMap> strings = RContext.getInstance().stringMap; XdrInputFormat(InputStream is) { super(is); if (is instanceof PByteArrayInputStream) { // we already have the data and we have read the beginning PByteArrayInputStream pbis = (PByteArrayInputStream) is; defaultBuffer = new Buffer(pbis.getData()); defaultBuffer.size = pbis.getData().length; defaultBuffer.offset = pbis.pos(); } else { defaultBuffer = new Buffer(new byte[READ_BUFFER_SIZE]); defaultBuffer.size = 0; defaultBuffer.offset = 0; } } @Override int readInt() throws IOException { return ensureData(4).readInt(); } @Override double readDouble() throws IOException { return ensureData(8).readDouble(); } @Override String readString(int len) throws IOException { return ensureData(len).readString(len); } @Override void readRaw(byte[] data) throws IOException { ensureData(data.length).readRaw(data); } private Buffer ensureData(int n) throws IOException { Buffer usedBuffer; if (n > defaultBuffer.buf.length) { if (is instanceof PByteArrayInputStream) { // If the input stream is instance of PByteArrayInputStream, the buffer is // preloaded and thus no more data can be read beyond the current buffer. throw new IOException("Premature EOF"); } // create an enlarged copy of the default buffer byte[] enlargedBuf = new byte[n]; System.arraycopy(defaultBuffer.buf, defaultBuffer.offset, enlargedBuf, defaultBuffer.offset, defaultBuffer.size - defaultBuffer.offset); usedBuffer = new Buffer(enlargedBuf); usedBuffer.offset = defaultBuffer.offset; usedBuffer.size = defaultBuffer.size; // reset the default buffer defaultBuffer.offset = defaultBuffer.size = 0; usedBuffer.readData(n); // The previous statement should entirely fill the temporary buffer. // It is assumed that the caller will read n bytes, making the temporary buffer // disposable. Next time, the default buffer will be used again, unless // n > defaultBuffer.buf.length. assert usedBuffer.size == n; } else { usedBuffer = defaultBuffer; usedBuffer.readData(n); } return usedBuffer; } } |
blob | long method | t | t | f | long method | blob | 0 | 2291 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/RSerialize.java/#L1097-L1252 | 1 | 204 | 2291 | major |
| 2569 | {"message": "YES I found bad smells, the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 14876 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 2569 | 14876 | major |
| 2056 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | Feature envy, 2Long parameter list | t | f | f | .Feature envy, 2.Long parameter list | data class | 0 | 12950 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2056 | 12950 | major |
| 2692 | Yes I found bad smells. The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | blob | 0 | 15301 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 2 | 2692 | 15301 | minor |
| 801 | { "response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Long parameter list", "3. Feature envy", "4. Data class", "5. Message chains", "6. Lazy class", "7. Duplicate code", "8. Comments"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
blob | 1. long method, 2. long parameter list, 3. feature envy, 4. data class, 5. message chains, 6. lazy class, 7. duplicate code, 8. comments | t | t | f | 1. long method, 2. long parameter list, 3. feature envy, 4. data class, 5. message chains, 6. lazy class, 7. duplicate code, 8. comments | blob | 0 | 7591 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 2 | 801 | 7591 | major |
| 975 | YES I found bad smells The bad smells are: 1. Getter and setter methods are unnecessary and cluttering the code. 2. Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive. 3. Class is not doing anything, no methods or logic are defined. 4. Class name "Product" is too broad and doesn't specify its purpose or responsibility. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Getter and setter methods are unnecessary and cluttering the code2 Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive3 Class is not doing anything, no methods or logic are defined4 Class name "Product" is too broad and doesn't specify its purpose or responsibility | t | f | f | . Getter and setter methods are unnecessary and cluttering the code.2. Naming convention is not clear, "d" as parameter and "id" as variable name are not descriptive.3. Class is not doing anything, no methods or logic are defined.4. Class name "Product" is too broad and doesn't specify its purpose or responsibility. | data class | 0 | 8780 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 975 | 8780 | major |
| 816 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class WSDLReaderImpl extends com.ibm.wsdl.xml.WSDLReaderImpl { private WSDLFactory _localFactory; WSDLReaderImpl(WSDLFactory factory) { _localFactory = factory; } @Override protected WSDLFactory getWSDLFactory() throws WSDLException { return _localFactory; } @Override public Binding parseBinding(Element bindingEl, Definition def) throws WSDLException { Binding binding = super.parseBinding(bindingEl, def); binding.setDocumentationElement(null); return binding; } @Override public BindingFault parseBindingFault(Element bindingFaultEl, Definition def) throws WSDLException { BindingFault bindingFault = super.parseBindingFault(bindingFaultEl, def); bindingFault.setDocumentationElement(null); return bindingFault; } @Override public BindingInput parseBindingInput(Element bindingInputEl, Definition def) throws WSDLException { BindingInput bindingInput = super.parseBindingInput(bindingInputEl, def); bindingInput.setDocumentationElement(null); return bindingInput; } @Override public BindingOperation parseBindingOperation(Element bindingOperationEl, PortType portType, Definition def) throws WSDLException { BindingOperation bindingOperation = super.parseBindingOperation(bindingOperationEl, portType, def); bindingOperation.setDocumentationElement(null); return bindingOperation; } @Override public BindingOutput parseBindingOutput(Element bindingOutputEl, Definition def) throws WSDLException { BindingOutput BindingOutput = super.parseBindingOutput(bindingOutputEl, def); BindingOutput.setDocumentationElement(null); return BindingOutput; } @SuppressWarnings("rawtypes") @Override public Definition parseDefinitions(String documentBaseURI, Element defEl, Map importedDefs) throws WSDLException { Definition definition = super.parseDefinitions(documentBaseURI, defEl, importedDefs); definition.setDocumentationElement(null); return definition; } @Override public Fault parseFault(Element faultEl, Definition def) throws WSDLException { Fault fault = super.parseFault(faultEl, def); fault.setDocumentationElement(null); return fault; } @Override public Input parseInput(Element inputEl, Definition def) throws WSDLException { Input input = super.parseInput(inputEl, def); input.setDocumentationElement(null); return input; } @Override public Message parseMessage(Element msgEl, Definition def) throws WSDLException { Message message = super.parseMessage(msgEl, def); message.setDocumentationElement(null); return message; } @Override public Operation parseOperation(Element opEl, PortType portType, Definition def) throws WSDLException { Operation operation = super.parseOperation(opEl, portType, def); operation.setDocumentationElement(null); return operation; } @Override public Output parseOutput(Element outputEl, Definition def) throws WSDLException { Output output = super.parseOutput(outputEl, def); output.setDocumentationElement(null); return output; } @Override public Part parsePart(Element partEl, Definition def) throws WSDLException { Part part = super.parsePart(partEl, def); part.setDocumentationElement(null); return part; } @Override public Port parsePort(Element portEl, Definition def) throws WSDLException { Port Port = super.parsePort(portEl, def); Port.setDocumentationElement(null); return Port; } @Override public PortType parsePortType(Element portTypeEl, Definition def) throws WSDLException { PortType portType = super.parsePortType(portTypeEl, def); portType.setDocumentationElement(null); return portType; } @Override public Service parseService(Element serviceEl, Definition def) throws WSDLException { Service service = super.parseService(serviceEl, def); service.setDocumentationElement(null); return service; } @Override public Types parseTypes(Element typesEl, Definition def) throws WSDLException { Types types = super.parseTypes(typesEl, def); types.setDocumentationElement(null); return types; } } |
blob | long method | t | t | f | long method | blob | 0 | 7667 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/wsdl/WSDLReaderImpl.java/#L52-L177 | 1 | 816 | 7667 | major |
| 2620 | YES I found bad smells. The bad smells are: 1. Duplication of code in the overridden methods. 2. The code has a high level of abstraction which may make it difficult to read and understand. 3. The use of native methods may make the code difficult to maintain and debug. 4. The use of magic numbers in the native method calls. 5. The use of a PrivilegedAction interface without specifying the type of privilege. 6. The use of AccessController without specifying the type of access control. 7. The class name does not accurately describe the purpose of the class. 8. The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options. 9. The code violates the Open-Closed Principle as it is not easily extendable to support new options. 10. The code has low cohesion as the overridden methods all access different native methods. 11. The use of a default constructor which does not initialize any fields or perform any operations. 12. The use of empty catch blocks in the native method calls. 13. The lack of error handling in the native method calls. 14. The use of mutable parameters in the native method calls may lead to unexpected behavior. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Duplication of code in the overridden methods2 The code has a high level of abstraction which may make it difficult to read and understand3 The use of native methods may make the code difficult to maintain and debug4 The use of magic numbers in the native method calls5 The use of a PrivilegedAction interface without specifying the type of privilege6 The use of AccessController without specifying the type of access control7 The class name does not accurately describe the purpose of the class8 The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options9 The code violates the Open-Closed Principle as it is not easily extendable to support new options | t | f | f | . Duplication of code in the overridden methods.2. The code has a high level of abstraction which may make it difficult to read and understand.3. The use of native methods may make the code difficult to maintain and debug.4. The use of magic numbers in the native method calls.5. The use of a PrivilegedAction interface without specifying the type of privilege.6. The use of AccessController without specifying the type of access control.7. The class name does not accurately describe the purpose of the class.8. The code violates the Single Responsibility Principle by having multiple methods for setting and getting different options.9. The code violates the Open-Closed Principle as it is not easily extendable to support new options. | data class | 0 | 15054 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 2620 | 15054 | minor |
| 31 | { "message": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void displayWarning(final String message) { notificationMessage.showNotification(SPUIStyleDefinitions.SP_NOTIFICATION_WARNING_MESSAGE_STYLE, null, message, true); } |
feature envy | Not specified | f | f | f | false | 0 | 729 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/UINotification.java/#L52-L55 | 2 | 31 | 729 | minor | |
| 796 | {"message": "YES I found bad smells", "bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 7556 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 1 | 796 | 7556 | minor |
| 4513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11975 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 4513 | 11975 | minor |
| 2691 | YES I found bad smells the bad smells are: 1. Parameter list 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | Parameter list 2 Long method 3 Feature envy | t | f | f | . Parameter list 2. Long method 3. Feature envy | data class | 0 | 15300 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 2691 | 15300 | minor |
| 1742 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Blob, Long Method | t | f | f | Blob, Long Method | data class | 0 | 11845 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 1742 | 11845 | minor |
| 4637 | { "output": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12373 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L54340-L54409 | 1 | 4637 | 12373 | minor | ||
| 179 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BrocadeVcsApi { private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class); private final String _host; private final String _adminuser; private final String _adminpass; protected DefaultHttpClient _client; protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { String url; try { url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Brocade Switch API URL", e); throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); } if ("post".equalsIgnoreCase(type)) { return new HttpPost(url); } else if ("get".equalsIgnoreCase(type)) { return new HttpGet(url); } else if ("delete".equalsIgnoreCase(type)) { return new HttpDelete(url); } else if ("patch".equalsIgnoreCase(type)) { return new HttpPatch(url); } else { throw new BrocadeVcsApiException("Requesting unknown method type"); } } public BrocadeVcsApi(String address, String username, String password) { _host = address; _adminuser = username; _adminpass = password; _client = new DefaultHttpClient(); _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); } /* * Get Operational Status */ public Output getSwitchStatus() throws BrocadeVcsApiException { return executeRetreiveStatus(Constants.STATUS_URI); } /* * Creates a new virtual network. */ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (createInterfaceVlan(vlanId)) { final PortProfile portProfile = createPortProfile(vlanId, networkId); if (portProfile != null) { return activatePortProfile(portProfile); } } return false; } /* * Activates a port-profile. */ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); portProfile.setVlanProfile(null); final Activate activate = new Activate(); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Creates AMPP port-profile. */ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); if (executeCreateObject(portProfile, Constants.URI)) { if (createVlanSubProfile(vlanId, portProfile)) { return portProfile; } } return null; } /* * Create vlan sub-profile for port-profile */ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final VlanProfile vlanProfile = new VlanProfile(); portProfile.setVlanProfile(vlanProfile); if (executeUpdateObject(portProfile, Constants.URI)) { return configureVlanSubProfile(vlanId, portProfile); } return false; } /* * Configures vlan sub-profile for port-profile. * - configure L2 mode for vlan sub-profile * - configure trunk mode for vlan sub-profile * - configure allowed VLANs for vlan sub-profile */ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final SwitchportBasic switchPortBasic = new SwitchportBasic(); final Basic basic = new Basic(); switchPortBasic.setBasic(basic); portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); // configure L2 mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { VlanProfile vlanProfile = new VlanProfile(); Switchport switchPort = new Switchport(); final Mode mode = new Mode(); mode.setVlanMode("trunk"); switchPort.setMode(mode); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); // configure trunk mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { vlanProfile = new VlanProfile(); switchPort = new Switchport(); final Trunk trunk = new Trunk(); final Allowed allowed = new Allowed(); final Allowed.Vlan allowedVlan = new Allowed.Vlan(); allowedVlan.setAdd(vlanId); allowed.setVlan(allowedVlan); trunk.setAllowed(allowed); switchPort.setTrunk(trunk); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); //configure allowed VLANs for vlan sub-profile return executeUpdateObject(portProfile, Constants.URI); } } return false; } /* * Creates a vlan interface. */ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Associates a MAC address to virtual network. */ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Disassociates a MAC address from virtual network. */ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setOperation("delete"); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes a new virtual network. */ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (deactivatePortProfile(networkId)) { if (deletePortProfile(networkId)) { return deleteInterfaceVlan(vlanId); } } return false; } /* * Deletes a vlan interface. */ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setOperation("delete"); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Deactivates a port-profile. */ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Activate activate = new Activate(); activate.setOperation("delete"); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes AMPP port-profile. */ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); portProfile.setOperation("delete"); //deletes port-profile return executeUpdateObject(portProfile, Constants.URI); } protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { final boolean result = true; if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpPatch pm = (HttpPatch)createMethod("patch", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to update object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); return result; } protected String convertToString(T object) throws BrocadeVcsApiException { final StringWriter stringWriter = new StringWriter(); try { final JAXBContext context = JAXBContext.newInstance(object.getClass()); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, stringWriter); } catch (final JAXBException e) { s_logger.error("Failed to convert object to string : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); } final String str = stringWriter.toString(); s_logger.info(str); return str; } protected Output convertToXML(String object) throws BrocadeVcsApiException { Output output = null; try { final JAXBContext context = JAXBContext.newInstance(Output.class); final StringReader reader = new StringReader(object); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(reader); if (result instanceof Output) { output = (Output)result; s_logger.info(output); } } catch (final JAXBException e) { s_logger.error("Failed to convert string to object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); } return output; } protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final boolean result = true; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to create object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return result; } protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while ((readLine = br.readLine()) != null) { s_logger.debug(readLine); sb.append(readLine); } } catch (final Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); } protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpDelete dm = (HttpDelete)createMethod("delete", uri); dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); final HttpResponse response = executeMethod(dm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to delete object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); } dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); } protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { HttpResponse response = null; try { response = _client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); response = _client.execute(method); } } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Brocade Switch", e); method.releaseConnection(); throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); } return response; } private String responseToErrorMessage(HttpResponse response) throws IOException { if ("text/html".equals(response.getEntity().getContentType().getValue())) { try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } } return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2055 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java/#L63-L542 | 2 | 179 | 2055 | major |
| 2007 | { "YES I found bad smells": true, "the bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | long method | t | t | f | long method | blob | 0 | 12736 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 2 | 2007 | 12736 | critical |
| 3228 | {"response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Large class", "3. Feature envy", "4. Comments with little value" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } } |
blob | 1. long method, 2. large class, 3. feature envy, 4. comments with little value | t | t | f | 1. long method, 2. large class, 3. feature envy, 4. comments with little value | blob | 0 | 5328 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 | 2 | 3228 | 5328 | critical |
| 2079 | YES I found bad smells, the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 13060 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 2079 | 13060 | major |
| 246 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 2 | 246 | 2654 | minor |
| 896 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Argument { public static Argument SKIP_TESTS = Argument.arg("skipTests"); @NonNull String name; @NonNull Optional> value; private Argument(String name, ArgumentValue value) { this(name, Optional.of(value)); } static Argument of(String name) { return new Argument(name, Optional.empty()); } /** * Enables the given comma-separated profiles for the {@link CommandLine}. * * @param name must not be {@literal null} or empty. * @return */ public static Argument profile(String name, String... others) { Assert.hasText(name, "Profiles must not be null or empty!"); Assert.notNull(others, "Other profiles must not be null!"); String profiles = Stream.concat(Stream.of(name), Arrays.stream(others)).collect(Collectors.joining(",")); return Argument.of("-P".concat(profiles)); } public static Argument arg(String name) { return Argument.of("-D".concat(name)); } public static Argument debug() { return Argument.of("-X"); } public Argument withValue(Object value) { return new Argument(name, ArgumentValue.of(value)); } public Argument withQuotedValue(Object value) { return new Argument(name, ArgumentValue.of(value, it -> String.format("\"%s\"", it.toString()))); } public Argument withValue(Masked masked) { return new Argument(name, ArgumentValue.of(masked)); } public String toCommandLineArgument() { return toNameValuePair(value.map(ArgumentValue::toCommandLine)); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return toNameValuePair(value.map(Object::toString)); } private String toNameValuePair(Optional source) { return source// .map(it -> String.format("%s=%s", name, it))// .orElse(name); } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class ArgumentValue { private final @NonNull T value; private final @NonNull Optional> preparer; private final @NonNull Optional> toString; public static ArgumentValue of(T value) { return new ArgumentValue<>(value, Optional.empty(), Optional.empty()); } public static ArgumentValue of(T value, Function preparer) { return new ArgumentValue<>(value, Optional.of(preparer), Optional.empty()); } /** * Returns an {@link ArgumentValue} for the given {@link Masked} value. * * @param masked must not be {@literal null}. * @return */ public static ArgumentValue of(T masked) { return new ArgumentValue<>(masked, Optional.empty(), Optional.of(it -> it.masked())); } /** * Returns the {@link String} variant of the argument value. * * @return */ public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return toString.map(it -> it.apply(value)).orElseGet(() -> toCommandLine()); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 8137 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L142-L257 | 2 | 896 | 8137 | minor |
| 925 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 8311 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 925 | 8311 | major |
| 470 | YES I found bad smells the bad smells are: 1. Long Method 2. Static Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings({ "unchecked", "rawtypes" }) public final class CorePlugin extends Plugin { public static final String PLUGIN_ID = "org.eclipse.buildship.core"; //$NON-NLS-1$ public static final String GRADLE_JOB_FAMILY = PLUGIN_ID + ".jobs"; private static CorePlugin plugin; // do not use generics-aware signature since this causes compilation troubles (JDK, Spock) // search the web for -target jsr14 to find out more about this obscurity private ServiceRegistration loggerService; private ServiceRegistration publishedGradleVersionsService; private ServiceRegistration workspaceOperationsService; private ServiceRegistration internalGradleWorkspaceService; private ServiceRegistration processStreamsProviderService; private ServiceRegistration gradleLaunchConfigurationService; private ServiceRegistration listenerRegistryService; // service tracker for each service to allow to register other service implementations of the // same type but with higher prioritization, useful for testing private ServiceTracker loggerServiceTracker; private ServiceTracker publishedGradleVersionsServiceTracker; private ServiceTracker workspaceOperationsServiceTracker; private ServiceTracker internalGradleWorkspaceServiceTracker; private ServiceTracker processStreamsProviderServiceTracker; private ServiceTracker gradleLaunchConfigurationServiceTracker; private ServiceTracker listenerRegistryServiceTracker; private DefaultModelPersistence modelPersistence; private ProjectChangeListener projectChangeListener; private SynchronizingBuildScriptUpdateListener buildScriptUpdateListener; private InvocationCustomizer invocationCustomizer; private ConfigurationManager configurationManager; private DefaultExternalLaunchConfigurationManager externalLaunchConfigurationManager; private ToolingApiOperationManager operationManager; private ExtensionManager extensionManager; @Override public void start(BundleContext bundleContext) throws Exception { super.start(bundleContext); plugin = this; ensureProxySettingsApplied(); registerServices(bundleContext); } @Override public void stop(BundleContext context) throws Exception { unregisterServices(); plugin = null; super.stop(context); } private void ensureProxySettingsApplied() throws Exception { // the proxy settings are set when the core.net plugin is started Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT); } private void registerServices(BundleContext context) { // store services with low ranking such that they can be overridden // during testing or the like Dictionary preferences = new Hashtable<>(); preferences.put(Constants.SERVICE_RANKING, 1); // initialize service trackers before the services are created this.loggerServiceTracker = createServiceTracker(context, Logger.class); this.publishedGradleVersionsServiceTracker = createServiceTracker(context, PublishedGradleVersionsWrapper.class); this.workspaceOperationsServiceTracker = createServiceTracker(context, WorkspaceOperations.class); this.internalGradleWorkspaceServiceTracker = createServiceTracker(context, InternalGradleWorkspace.class); this.processStreamsProviderServiceTracker = createServiceTracker(context, ProcessStreamsProvider.class); this.gradleLaunchConfigurationServiceTracker = createServiceTracker(context, GradleLaunchConfigurationManager.class); this.listenerRegistryServiceTracker = createServiceTracker(context, ListenerRegistry.class); // register all services this.loggerService = registerService(context, Logger.class, createLogger(), preferences); this.publishedGradleVersionsService = registerService(context, PublishedGradleVersionsWrapper.class, createPublishedGradleVersions(), preferences); this.workspaceOperationsService = registerService(context, WorkspaceOperations.class, createWorkspaceOperations(), preferences); this.internalGradleWorkspaceService = registerService(context, InternalGradleWorkspace.class, createGradleWorkspace(), preferences); this.processStreamsProviderService = registerService(context, ProcessStreamsProvider.class, createProcessStreamsProvider(), preferences); this.gradleLaunchConfigurationService = registerService(context, GradleLaunchConfigurationManager.class, createGradleLaunchConfigurationManager(), preferences); this.listenerRegistryService = registerService(context, ListenerRegistry.class, createListenerRegistry(), preferences); this.modelPersistence = DefaultModelPersistence.createAndRegister(); this.projectChangeListener = ProjectChangeListener.createAndRegister(); this.buildScriptUpdateListener = SynchronizingBuildScriptUpdateListener.createAndRegister(); this.invocationCustomizer = new InvocationCustomizerCollector(); this.configurationManager = new DefaultConfigurationManager(); this.externalLaunchConfigurationManager = DefaultExternalLaunchConfigurationManager.createAndRegister(); this.operationManager = new DefaultToolingApiOperationManager(); this.extensionManager = new DefaultExtensionManager(); } private ServiceTracker createServiceTracker(BundleContext context, Class clazz) { ServiceTracker serviceTracker = new ServiceTracker(context, clazz.getName(), null); serviceTracker.open(); return serviceTracker; } private ServiceRegistration registerService(BundleContext context, Class clazz, T service, Dictionary properties) { return context.registerService(clazz.getName(), service, properties); } private EclipseLogger createLogger() { Map tracingEnablement = Maps.newHashMap(); for (TraceScope scope : CoreTraceScopes.values()) { String option = Platform.getDebugOption("org.eclipse.buildship.core/trace/" + scope.getScopeKey()); tracingEnablement.put(scope, "true".equalsIgnoreCase(option)); } return new EclipseLogger(getLog(), PLUGIN_ID, tracingEnablement); } private PublishedGradleVersionsWrapper createPublishedGradleVersions() { return new PublishedGradleVersionsWrapper(); } private WorkspaceOperations createWorkspaceOperations() { return new DefaultWorkspaceOperations(); } private InternalGradleWorkspace createGradleWorkspace() { return new DefaultGradleWorkspace(); } private ProcessStreamsProvider createProcessStreamsProvider() { return new StdProcessStreamsProvider(); } private GradleLaunchConfigurationManager createGradleLaunchConfigurationManager() { return new DefaultGradleLaunchConfigurationManager(); } private ListenerRegistry createListenerRegistry() { return new DefaultListenerRegistry(); } private void unregisterServices() { this.externalLaunchConfigurationManager.unregister(); this.buildScriptUpdateListener.close(); this.projectChangeListener.close(); this.modelPersistence.close(); this.listenerRegistryService.unregister(); this.gradleLaunchConfigurationService.unregister(); this.processStreamsProviderService.unregister(); this.internalGradleWorkspaceService.unregister(); this.workspaceOperationsService.unregister(); this.publishedGradleVersionsService.unregister(); this.loggerService.unregister(); this.listenerRegistryServiceTracker.close(); this.gradleLaunchConfigurationServiceTracker.close(); this.processStreamsProviderServiceTracker.close(); this.internalGradleWorkspaceServiceTracker.close(); this.workspaceOperationsServiceTracker.close(); this.publishedGradleVersionsServiceTracker.close(); this.loggerServiceTracker.close(); } public static CorePlugin getInstance() { return plugin; } public static Logger logger() { return (Logger) getInstance().loggerServiceTracker.getService(); } public static PublishedGradleVersionsWrapper publishedGradleVersions() { return (PublishedGradleVersionsWrapper) getInstance().publishedGradleVersionsServiceTracker.getService(); } public static WorkspaceOperations workspaceOperations() { return (WorkspaceOperations) getInstance().workspaceOperationsServiceTracker.getService(); } public static InternalGradleWorkspace internalGradleWorkspace() { return (InternalGradleWorkspace) getInstance().internalGradleWorkspaceServiceTracker.getService(); } public static ProcessStreamsProvider processStreamsProvider() { return (ProcessStreamsProvider) getInstance().processStreamsProviderServiceTracker.getService(); } public static GradleLaunchConfigurationManager gradleLaunchConfigurationManager() { return (GradleLaunchConfigurationManager) getInstance().gradleLaunchConfigurationServiceTracker.getService(); } public static ListenerRegistry listenerRegistry() { return (ListenerRegistry) getInstance().listenerRegistryServiceTracker.getService(); } public static ModelPersistence modelPersistence() { return getInstance().modelPersistence; } public static InvocationCustomizer invocationCustomizer() { return getInstance().invocationCustomizer; } public static ConfigurationManager configurationManager() { return getInstance().configurationManager; } public static ExternalLaunchConfigurationManager externalLaunchConfigurationManager() { return getInstance().externalLaunchConfigurationManager; } public static ToolingApiOperationManager operationManager() { return getInstance().operationManager; } public static ExtensionManager extensionManager() { return getInstance().extensionManager; } } |
blob | Long Method2 Static Method | t | f | f | . Long Method2. Static Method | blob | 0 | 4563 | https://github.com/eclipse/buildship/blob/3111a7a9fe3e22d6123366686874ecd42aa2a53a/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/CorePlugin.java/#L70-L282 | 2 | 470 | 4563 | major |
| 843 | {"response": "YES I found bad smells", "bad smells are:": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 7804 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 2 | 843 | 7804 | critical |
| 104 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } } |
blob | data class | t | t | f | data class | blob | 0 | 1359 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 | 1 | 104 | 1359 | minor |
| 1110 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9884 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 2 | 1110 | 9884 | minor |
| 2008 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | 1. long method, 2. blob | t | t | f | 1. long method, 2. blob | data class | 0 | 12738 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 1 | 2008 | 12738 | critical |
| 2490 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Duplicate code 5. Inappropriate commenting 6. Empty method 7. Duplicated code 8. Long parameter list 9. Inappropriate error handling 10. Unnecessary variable 11. Useless constructor 12. Inconsistent naming convention 13. Lazy class 14. Poor exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Duplicate code5 Inappropriate commenting6 Empty method7 Duplicated code8 Long parameter list9 Inappropriate error handling | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Duplicate code5. Inappropriate commenting6. Empty method7. Duplicated code8. Long parameter list9. Inappropriate error handling | data class | 0 | 14617 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 2490 | 14617 | minor |
| 3618 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Magic Numbers 5. Non-Descriptive Variable Names 6. Code Clutter | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface JsonObjectMapper { default String toJson(Object value) throws IOException { return null; } default void toJson(Object value, Writer writer) throws IOException { } default N toJsonNode(Object value) throws IOException { return null; } default T fromJson(Object json, Class valueType) throws IOException { return null; } /** * Deserialize a JSON to an expected {@link ResolvableType}. * @param json the JSON to deserialize * @param valueType the {@link ResolvableType} for the target object. * @param the expected object type * @return deserialization result object * @throws IOException a JSON parsing exception * @since 5.2 */ default T fromJson(Object json, ResolvableType valueType) throws IOException { return null; } default T fromJson(Object json, Map javaTypes) throws IOException { return null; } default T fromJson(P parser, Type valueType) throws IOException { return null; } default void populateJavaTypes(Map map, Object object) { Class targetClass = object.getClass(); Class contentClass = null; Class keyClass = null; map.put(JsonHeaders.TYPE_ID, targetClass); if (object instanceof Collection && !((Collection) object).isEmpty()) { Object firstElement = ((Collection) object).iterator().next(); if (firstElement != null) { contentClass = firstElement.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } } if (object instanceof Map && !((Map) object).isEmpty()) { Object firstValue = ((Map) object).values().iterator().next(); if (firstValue != null) { contentClass = firstValue.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } Object firstKey = ((Map) object).keySet().iterator().next(); if (firstKey != null) { keyClass = firstKey.getClass(); map.put(JsonHeaders.KEY_TYPE_ID, keyClass); } } map.put(JsonHeaders.RESOLVABLE_TYPE, buildResolvableType(targetClass, contentClass, keyClass)); } static ResolvableType buildResolvableType(Class targetClass, @Nullable Class contentClass, @Nullable Class keyClass) { if (keyClass != null) { return TypeDescriptor .map(targetClass, TypeDescriptor.valueOf(keyClass), TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else if (contentClass != null) { return TypeDescriptor .collection(targetClass, TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else { return ResolvableType.forClass(targetClass); } } } |
blob | Long Method2 Feature Envy3 Duplicate Code4 Magic Numbers5 Non-Descriptive Variable Names6 Code Clutter | t | f | f | . Long Method2. Feature Envy3. Duplicate Code4. Magic Numbers5. Non-Descriptive Variable Names6. Code Clutter | blob | 0 | 8109 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-core/src/main/java/org/springframework/integration/support/json/JsonObjectMapper.java/#L41-L130 | 2 | 3618 | 8109 | minor |
| 1051 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9477 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1051 | 9477 | major |
| 467 | YES I found bad smells. The bad smells are: 1. Inconsistent spacing and indentation 2. Use of vague variable and method names 3. Lack of comments and documentation for methods 4. Use of EnumSet for parameter types instead of more specific types 5. Mixing of variable types in method parameters 6. Use of abbreviated variable names (e.g. cdata) 7. Use of multiple return statements instead of a single return statement 8. Inconsistent use of parentheses for method calls 9. Mixing of code with comments 10. Lack of clarity in method functionality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Element(endTag=false) public interface LINK extends Attrs, _Child { // $charset omitted /** URI for linked resource * @param uri the URI * @return the current element builder */ LINK $href(String uri); /** language code * @param cdata the code * @return the current element builder */ LINK $hreflang(String cdata); /** advisory content type * @param cdata the type * @return the current element builder */ LINK $type(String cdata); /** forward link types * @param linkTypes the types * @return the current element builder */ LINK $rel(EnumSet linkTypes); /** * forward link types. * @param linkTypes space-separated link types * @return the current element builder */ LINK $rel(String linkTypes); // $rev omitted. Instead of rev="made", use rel="author" /** for rendering on these media * @param mediaTypes the media types * @return the current element builder */ LINK $media(EnumSet mediaTypes); /** * for rendering on these media. * @param mediaTypes comma-separated list of media * @return the current element builder */ LINK $media(String mediaTypes); } |
data class | Inconsistent spacing and indentation2 Use of vague variable and method names 3 Lack of comments and documentation for methods 4 Use of EnumSet for parameter types instead of more specific types 5 Mixing of variable types in method parameters 6 Use of abbreviated variable names (eg cdata) 7 Use of multiple return statements instead of a single return statement 8 Inconsistent use of parentheses for method calls 9 Mixing of code with comments | t | f | f | . Inconsistent spacing and indentation2. Use of vague variable and method names 3. Lack of comments and documentation for methods 4. Use of EnumSet for parameter types instead of more specific types 5. Mixing of variable types in method parameters 6. Use of abbreviated variable names (e.g. cdata) 7. Use of multiple return statements instead of a single return statement 8. Inconsistent use of parentheses for method calls 9. Mixing of code with comments | data class | 0 | 4538 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java/#L1772-L1820 | 2 | 467 | 4538 | major |
| 2544 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 14788 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 | 2 | 2544 | 14788 | minor |
| 22 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void hide() { view.close(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 686 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/progressor/ProgressMonitorPresenter.java/#L74-L76 | 1 | 22 | 686 | minor |
| 2428 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class createJob_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createJob_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createJob_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 14450 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/AuroraSchedulerManager.java/#L2760-L2805 | 2 | 2428 | 14450 | minor |
| 2202 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 13505 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 2 | 2202 | 13505 | major |
| 792 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7536 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 792 | 7536 | minor |
| 1718 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Class with too many responsibilities 5. Use of static methods and variables 6. Poor variable naming (ex. jmx_property_ids, SQLServerPropertyIds) 7. Violation of Single Responsibility Principle (SRP) 8. Possible data duplication with the use of multiple maps for resource metrics. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Long method 2 Feature envy 3 Nested loops 4 Class with too many responsibilities 5 Use of static methods and variables 6 Poor variable naming (ex jmx_property_ids, SQLServerPropertyIds) 7 Violation of Single Responsibility Principle (SRP) 8 Possible data duplication with the use of multiple maps for resource metrics | t | f | f | . Long method 2. Feature envy 3. Nested loops 4. Class with too many responsibilities 5. Use of static methods and variables 6. Poor variable naming (ex. jmx_property_ids, SQLServerPropertyIds) 7. Violation of Single Responsibility Principle (SRP) 8. Possible data duplication with the use of multiple maps for resource metrics. | data class | 0 | 11785 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 1718 | 11785 | minor |
| 585 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5805 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 2 | 585 | 5805 | critical |
| 1445 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10981 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 1445 | 10981 | major |
| 566 | { "message": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class ProxiedNiFiClient implements NiFiClient { private final String proxiedEntity; private final NiFiClient wrappedClient; public ProxiedNiFiClient(final NiFiClient wrappedClient, final String proxiedEntity) { this.proxiedEntity = proxiedEntity; this.wrappedClient = wrappedClient; } @Override public ControllerClient getControllerClient() { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getControllerClientForProxiedEntities(proxiedEntity); } @Override public ControllerClient getControllerClientForToken(String token) { return wrappedClient.getControllerClientForToken(token); } @Override public FlowClient getFlowClient() { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getFlowClientForProxiedEntities(proxiedEntity); } @Override public FlowClient getFlowClientForToken(String token) { return wrappedClient.getFlowClientForToken(token); } @Override public ProcessGroupClient getProcessGroupClient() { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getProcessGroupClientForProxiedEntities(proxiedEntity); } @Override public ProcessGroupClient getProcessGroupClientForToken(String token) { return wrappedClient.getProcessGroupClientForToken(token); } @Override public VersionsClient getVersionsClient() { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForProxiedEntities(String... proxiedEntity) { return wrappedClient.getVersionsClientForProxiedEntities(proxiedEntity); } @Override public VersionsClient getVersionsClientForToken(String token) { return wrappedClient.getVersionsClientForToken(token); } @Override public void close() throws IOException { wrappedClient.close(); } } |
data class | blob | t | t | f | blob | data class | 0 | 5719 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiClientFactory.java/#L113-L187 | 1 | 566 | 5719 | critical |
| 343 | YES I found bad smells the bad smells are: 1. Class is too small 2. Useless parentheses 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NamespaceFilter extends XMLFilterImpl { private static final InputSource EMPTY_INPUT_SOURCE = new InputSource(new ByteArrayInputStream(new byte[0])); public NamespaceFilter(XMLReader xmlReader) { super(xmlReader); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return EMPTY_INPUT_SOURCE; } } |
data class | Class is too small2 Useless parentheses3 Long method | t | f | f | . Class is too small2. Useless parentheses3. Long method | data class | 0 | 3503 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/sun/JaxbSun.java/#L96-L106 | 2 | 343 | 3503 | major |
| 1909 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12397 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 1909 | 12397 | minor |
| 1243 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10415 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 1243 | 10415 | minor |
| 2329 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14149 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 2329 | 14149 | minor |
| 1251 | {"output": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | "NO, I did not find any bad smell"} | f | f | f | "NO, I did not find any bad smell"} | blob | 0 | 10441 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 1251 | 10441 | major |
| 2276 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13775 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 2276 | 13775 | major |
| 84 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class MonoWhen extends Mono implements SourceProducer { final boolean delayError; final Publisher[] sources; final Iterable> sourcesIterable; MonoWhen(boolean delayError, Publisher... sources) { this.delayError = delayError; this.sources = Objects.requireNonNull(sources, "sources"); this.sourcesIterable = null; } MonoWhen(boolean delayError, Iterable> sourcesIterable) { this.delayError = delayError; this.sources = null; this.sourcesIterable = Objects.requireNonNull(sourcesIterable, "sourcesIterable"); } @SuppressWarnings("unchecked") @Nullable Mono whenAdditionalSource(Publisher source) { Publisher[] oldSources = sources; if (oldSources != null) { int oldLen = oldSources.length; Publisher[] newSources = new Publisher[oldLen + 1]; System.arraycopy(oldSources, 0, newSources, 0, oldLen); newSources[oldLen] = source; return new MonoWhen(delayError, newSources); } return null; } @SuppressWarnings("unchecked") @Override public void subscribe(CoreSubscriber actual) { Publisher[] a; int n = 0; if (sources != null) { a = sources; n = a.length; } else { a = new Publisher[8]; for (Publisher m : sourcesIterable) { if (n == a.length) { Publisher[] b = new Publisher[n + (n >> 2)]; System.arraycopy(a, 0, b, 0, n); a = b; } a[n++] = m; } } if (n == 0) { Operators.complete(actual); return; } WhenCoordinator parent = new WhenCoordinator(actual, n, delayError); actual.onSubscribe(parent); parent.subscribe(a); } @Override public Object scanUnsafe(Attr key) { if (key == Attr.DELAY_ERROR) return delayError; return null; } static final class WhenCoordinator extends Operators.MonoSubscriber { final WhenInner[] subscribers; final boolean delayError; volatile int done; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater DONE = AtomicIntegerFieldUpdater.newUpdater(WhenCoordinator.class, "done"); @SuppressWarnings("unchecked") WhenCoordinator(CoreSubscriber subscriber, int n, boolean delayError) { super(subscriber); this.delayError = delayError; subscribers = new WhenInner[n]; for (int i = 0; i < n; i++) { subscribers[i] = new WhenInner(this); } } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.TERMINATED) { return done == subscribers.length; } if (key == Attr.BUFFERED) { return subscribers.length; } if (key == Attr.DELAY_ERROR) { return delayError; } return super.scanUnsafe(key); } @Override public Stream inners() { return Stream.of(subscribers); } void subscribe(Publisher[] sources) { WhenInner[] a = subscribers; for (int i = 0; i < a.length; i++) { sources[i].subscribe(a[i]); } } void signalError(Throwable t) { if (delayError) { signal(); } else { int n = subscribers.length; if (DONE.getAndSet(this, n) != n) { cancel(); actual.onError(t); } } } @SuppressWarnings("unchecked") void signal() { WhenInner[] a = subscribers; int n = a.length; if (DONE.incrementAndGet(this) != n) { return; } Throwable error = null; Throwable compositeError = null; for (int i = 0; i < a.length; i++) { WhenInner m = a[i]; Throwable e = m.error; if (e != null) { if (compositeError != null) { //this is ok as the composite created below is never a singleton compositeError.addSuppressed(e); } else if (error != null) { compositeError = Exceptions.multiple(error, e); } else { error = e; } } } if (compositeError != null) { actual.onError(compositeError); } else if (error != null) { actual.onError(error); } else { actual.onComplete(); } } @Override public void cancel() { if (!isCancelled()) { super.cancel(); for (WhenInner ms : subscribers) { ms.cancel(); } } } } static final class WhenInner implements InnerConsumer { final WhenCoordinator parent; volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater S = AtomicReferenceFieldUpdater.newUpdater(WhenInner.class, Subscription.class, "s"); Throwable error; WhenInner(WhenCoordinator parent) { this.parent = parent; } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.CANCELLED) { return s == Operators.cancelledSubscription(); } if (key == Attr.PARENT) { return s; } if (key == Attr.ACTUAL) { return parent; } if (key == Attr.ERROR) { return error; } return null; } @Override public Context currentContext() { return parent.currentContext(); } @Override public void onSubscribe(Subscription s) { if (Operators.setOnce(S, this, s)) { s.request(Long.MAX_VALUE); } else { s.cancel(); } } @Override public void onNext(Object t) { } @Override public void onError(Throwable t) { error = t; parent.signalError(t); } @Override public void onComplete() { parent.signal(); } void cancel() { Operators.terminate(S, this); } } } |
blob | Not specified | f | f | f | false | 0 | 1201 | https://github.com/reactor/reactor-core/blob/3958e2fabf49e16229dda5df39e7cde46797ec51/reactor-core/src/main/java/reactor/core/publisher/MonoWhen.java/#L36-L292 | 2 | 84 | 1201 | major | |
| 2898 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2137 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 2 | 2898 | 2137 | critical | ||
| 1847 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | t | f | f | long method | 0 | 12172 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 1847 | 12172 | minor | ||
| 179 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BrocadeVcsApi { private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class); private final String _host; private final String _adminuser; private final String _adminpass; protected DefaultHttpClient _client; protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { String url; try { url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Brocade Switch API URL", e); throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); } if ("post".equalsIgnoreCase(type)) { return new HttpPost(url); } else if ("get".equalsIgnoreCase(type)) { return new HttpGet(url); } else if ("delete".equalsIgnoreCase(type)) { return new HttpDelete(url); } else if ("patch".equalsIgnoreCase(type)) { return new HttpPatch(url); } else { throw new BrocadeVcsApiException("Requesting unknown method type"); } } public BrocadeVcsApi(String address, String username, String password) { _host = address; _adminuser = username; _adminpass = password; _client = new DefaultHttpClient(); _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); } /* * Get Operational Status */ public Output getSwitchStatus() throws BrocadeVcsApiException { return executeRetreiveStatus(Constants.STATUS_URI); } /* * Creates a new virtual network. */ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (createInterfaceVlan(vlanId)) { final PortProfile portProfile = createPortProfile(vlanId, networkId); if (portProfile != null) { return activatePortProfile(portProfile); } } return false; } /* * Activates a port-profile. */ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); portProfile.setVlanProfile(null); final Activate activate = new Activate(); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Creates AMPP port-profile. */ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); if (executeCreateObject(portProfile, Constants.URI)) { if (createVlanSubProfile(vlanId, portProfile)) { return portProfile; } } return null; } /* * Create vlan sub-profile for port-profile */ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final VlanProfile vlanProfile = new VlanProfile(); portProfile.setVlanProfile(vlanProfile); if (executeUpdateObject(portProfile, Constants.URI)) { return configureVlanSubProfile(vlanId, portProfile); } return false; } /* * Configures vlan sub-profile for port-profile. * - configure L2 mode for vlan sub-profile * - configure trunk mode for vlan sub-profile * - configure allowed VLANs for vlan sub-profile */ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final SwitchportBasic switchPortBasic = new SwitchportBasic(); final Basic basic = new Basic(); switchPortBasic.setBasic(basic); portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); // configure L2 mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { VlanProfile vlanProfile = new VlanProfile(); Switchport switchPort = new Switchport(); final Mode mode = new Mode(); mode.setVlanMode("trunk"); switchPort.setMode(mode); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); // configure trunk mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { vlanProfile = new VlanProfile(); switchPort = new Switchport(); final Trunk trunk = new Trunk(); final Allowed allowed = new Allowed(); final Allowed.Vlan allowedVlan = new Allowed.Vlan(); allowedVlan.setAdd(vlanId); allowed.setVlan(allowedVlan); trunk.setAllowed(allowed); switchPort.setTrunk(trunk); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); //configure allowed VLANs for vlan sub-profile return executeUpdateObject(portProfile, Constants.URI); } } return false; } /* * Creates a vlan interface. */ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Associates a MAC address to virtual network. */ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Disassociates a MAC address from virtual network. */ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setOperation("delete"); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes a new virtual network. */ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (deactivatePortProfile(networkId)) { if (deletePortProfile(networkId)) { return deleteInterfaceVlan(vlanId); } } return false; } /* * Deletes a vlan interface. */ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setOperation("delete"); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Deactivates a port-profile. */ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Activate activate = new Activate(); activate.setOperation("delete"); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes AMPP port-profile. */ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); portProfile.setOperation("delete"); //deletes port-profile return executeUpdateObject(portProfile, Constants.URI); } protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { final boolean result = true; if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpPatch pm = (HttpPatch)createMethod("patch", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to update object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); return result; } protected String convertToString(T object) throws BrocadeVcsApiException { final StringWriter stringWriter = new StringWriter(); try { final JAXBContext context = JAXBContext.newInstance(object.getClass()); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, stringWriter); } catch (final JAXBException e) { s_logger.error("Failed to convert object to string : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); } final String str = stringWriter.toString(); s_logger.info(str); return str; } protected Output convertToXML(String object) throws BrocadeVcsApiException { Output output = null; try { final JAXBContext context = JAXBContext.newInstance(Output.class); final StringReader reader = new StringReader(object); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(reader); if (result instanceof Output) { output = (Output)result; s_logger.info(output); } } catch (final JAXBException e) { s_logger.error("Failed to convert string to object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); } return output; } protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final boolean result = true; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to create object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return result; } protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while ((readLine = br.readLine()) != null) { s_logger.debug(readLine); sb.append(readLine); } } catch (final Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); } protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpDelete dm = (HttpDelete)createMethod("delete", uri); dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); final HttpResponse response = executeMethod(dm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to delete object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); } dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); } protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { HttpResponse response = null; try { response = _client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); response = _client.execute(method); } } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Brocade Switch", e); method.releaseConnection(); throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); } return response; } private String responseToErrorMessage(HttpResponse response) throws IOException { if ("text/html".equals(response.getEntity().getContentType().getValue())) { try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } } return null; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2055 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java/#L63-L542 | 1 | 179 | 2055 | major |
| 294 | { "response": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | long method | t | t | f | long method | blob | 0 | 3086 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 1 | 294 | 3086 | critical |
| 1822 | SequenceFileReader YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | blob | 0 | 12100 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 2 | 1822 | 12100 | minor |
| 1938 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12477 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 | 1 | 1938 | 12477 | critical |
| 819 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 7677 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 | 1 | 819 | 7677 | critical |
| 365 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 3717 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 | 1 | 365 | 3717 | minor |
| 1251 | {"response":"YES I found bad smells","bad smells are:":"1. Long method, 2. Feature envy, 3. Complex condition, 4. Comments, 5. Exception swallowing, 6. Data class, 7. Shotgun surgery"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | 1. long method, 2. feature envy, 3. complex condition, 4. comments, 5. exception swallowing, 6. data class, 7. shotgun surgery | t | t | f | 1. long method, 2. feature envy, 3. complex condition, 4. comments, 5. exception swallowing, 6. data class, 7. shotgun surgery | blob | 0 | 10441 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 1251 | 10441 | major |
| 2513 | { "output": "YES I found bad smells", "detected_code_smells": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 14690 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 2513 | 14690 | minor |
| 2416 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | \n1. long method\n2. feature envy | t | t | f | \\n1. long method\\n2. feature envy | data class | 0 | 14420 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 2416 | 14420 | minor |
| 1751 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11859 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 1751 | 11859 | minor |
| 2278 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13783 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 2 | 2278 | 13783 | major |
| 4824 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JAXRSOutInterceptor extends AbstractOutDatabindingInterceptor { private static final Logger LOG = LogUtils.getL7dLogger(JAXRSOutInterceptor.class); private static final ResourceBundle BUNDLE = BundleUtils.getBundle(JAXRSOutInterceptor.class); public JAXRSOutInterceptor() { super(Phase.MARSHAL); } public void handleMessage(Message message) { ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); try { processResponse(providerFactory, message); } finally { ServerProviderFactory.releaseRequestState(providerFactory, message); } } @SuppressWarnings("resource") // Response shouldn't be closed here private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.isEmpty()) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response)responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class .getName()); serializeMessage(providerFactory, message, response, ori, true); } private int getStatus(Message message, int defaultValue) { Object customStatus = message.getExchange().get(Message.RESPONSE_CODE); return customStatus == null ? defaultValue : (Integer)customStatus; } private void serializeMessage(ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) { ResponseImpl response = (ResponseImpl)JAXRSUtils.copyResponseIfNeeded(theResponse); final Exchange exchange = message.getExchange(); boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod()); Object entity = response.getActualEntity(); if (headResponse && entity != null) { LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString()); entity = null; } Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke(); Annotation[] annotations = null; Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[]{}; Annotation[] responseAnns = response.getEntityAnnotations(); if (responseAnns != null) { annotations = new Annotation[staticAnns.length + responseAnns.length]; System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length); System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length); } else { annotations = staticAnns; } response.setStatus(getActualStatus(response.getStatus(), entity)); response.setEntity(entity, annotations); // Prepare the headers MultivaluedMap responseHeaders = prepareResponseHeaders(message, response, entity, firstTry); // Run the filters try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } // Write the entity entity = InjectionUtils.getEntity(response.getActualEntity()); setResponseStatus(message, getActualStatus(response.getStatus(), entity)); if (entity == null) { if (!headResponse) { responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0"); if (MessageUtils.getContextualBoolean(message, "remove.content.type.for.empty.response", false)) { responseHeaders.remove(HttpHeaders.CONTENT_TYPE); message.remove(Message.CONTENT_TYPE); } } HttpUtils.convertHeaderValuesToString(responseHeaders, true); return; } Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS); boolean ignoreWriters = ignoreWritersProp != null && Boolean.valueOf(ignoreWritersProp.toString()); if (ignoreWriters) { writeResponseToStream(message.getContent(OutputStream.class), entity); return; } MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE)); Class serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null; Class targetType = InjectionUtils.getRawResponseClass(entity); Type genericType = InjectionUtils.getGenericResponseType(invoked, serviceCls, response.getActualEntity(), targetType, exchange); targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType); annotations = response.getEntityAnnotations(); List writers = providerFactory .createMessageBodyWriterInterceptor(targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings()); OutputStream outOriginal = message.getContent(OutputStream.class); if (writers == null || writers.isEmpty()) { writeResponseErrorMessage(message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType); return; } try { boolean checkWriters = false; if (responseMediaType.isWildcardSubtype()) { Produces pM = AnnotationUtils.getMethodAnnotation(ori == null ? null : ori.getAnnotatedMethod(), Produces.class); Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class); checkWriters = pM == null && pC == null; } responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Response content type is: " + finalResponseContentType); } responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType); message.put(Message.CONTENT_TYPE, finalResponseContentType); boolean enabled = checkBufferingMode(message, writers, firstTry); try { try { JAXRSUtils.writeMessageBody(writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message); if (isResponseRedirected(message)) { return; } checkCachedStream(message, outOriginal, enabled); } finally { if (enabled) { OutputStream os = message.getContent(OutputStream.class); if (os != outOriginal && os instanceof CachedOutputStream) { os.close(); } message.setContent(OutputStream.class, outOriginal); message.put(XMLStreamWriter.class.getName(), null); } } } catch (Throwable ex) { logWriteError(firstTry, targetType, responseMediaType); handleWriteException(providerFactory, message, ex, firstTry); } } private MultivaluedMap prepareResponseHeaders(Message message, ResponseImpl response, Object entity, boolean firstTry) { MultivaluedMap responseHeaders = response.getMetadata(); @SuppressWarnings("unchecked") Map> userHeaders = (Map>)message.get(Message.PROTOCOL_HEADERS); if (firstTry && userHeaders != null) { responseHeaders.putAll(userHeaders); } if (entity != null) { Object customContentType = responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE); if (customContentType == null) { String initialResponseContentType = (String)message.get(Message.CONTENT_TYPE); if (initialResponseContentType != null) { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, initialResponseContentType); } } else { message.put(Message.CONTENT_TYPE, customContentType.toString()); } } message.put(Message.PROTOCOL_HEADERS, responseHeaders); setResponseDate(responseHeaders, firstTry); return responseHeaders; } private MediaType getResponseMediaType(Object mediaTypeHeader) { MediaType responseMediaType; if (mediaTypeHeader instanceof MediaType) { responseMediaType = (MediaType)mediaTypeHeader; } else { responseMediaType = mediaTypeHeader == null ? MediaType.WILDCARD_TYPE : JAXRSUtils.toMediaType(mediaTypeHeader.toString()); } return responseMediaType; } private int getActualStatus(int status, Object responseObj) { if (status == -1) { return responseObj == null ? 204 : 200; } return status; } private boolean checkBufferingMode(Message m, List writers, boolean firstTry) { if (!firstTry) { return false; } WriterInterceptor last = writers.get(writers.size() - 1); MessageBodyWriter w = ((WriterInterceptorMBW)last).getMBW(); Object outBuf = m.getContextualProperty(OUT_BUFFERING); boolean enabled = PropertyUtils.isTrue(outBuf); boolean configurableProvider = w instanceof AbstractConfigurableProvider; if (!enabled && outBuf == null && configurableProvider) { enabled = ((AbstractConfigurableProvider)w).getEnableBuffering(); } if (enabled) { boolean streamingOn = configurableProvider && ((AbstractConfigurableProvider)w).getEnableStreaming(); if (streamingOn) { m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter()); } else { m.setContent(OutputStream.class, new CachedOutputStream()); } } return enabled; } private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled) throws Exception { XMLStreamWriter writer = null; if (enabled) { writer = m.getContent(XMLStreamWriter.class); } else { writer = (XMLStreamWriter)m.get(XMLStreamWriter.class.getName()); } if (writer instanceof CachingXmlEventWriter) { CachingXmlEventWriter cache = (CachingXmlEventWriter)writer; if (cache.getEvents().size() != 0) { XMLStreamWriter origWriter = null; try { origWriter = StaxUtils.createXMLStreamWriter(osOriginal); for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origWriter); } } finally { StaxUtils.close(origWriter); } } m.setContent(XMLStreamWriter.class, null); return; } if (enabled) { OutputStream os = m.getContent(OutputStream.class); if (os != osOriginal && os instanceof CachedOutputStream) { CachedOutputStream cos = (CachedOutputStream)os; if (cos.size() != 0) { cos.writeCacheTo(osOriginal); } } } } private void logWriteError(boolean firstTry, Class cls, MediaType ct) { if (firstTry) { JAXRSUtils.logMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, ct); } } private void handleWriteException(ServerProviderFactory pf, Message message, Throwable ex, boolean firstTry) { Response excResponse = null; if (firstTry) { excResponse = JAXRSUtils.convertFaultToResponse(ex, message); } else { message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE); } if (excResponse == null) { setResponseStatus(message, 500); throw new Fault(ex); } serializeMessage(pf, message, excResponse, null, false); } private void writeResponseErrorMessage(Message message, OutputStream out, String name, Class cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } } private MediaType checkFinalContentType(MediaType mt, List writers, boolean checkWriters) { if (checkWriters) { int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1; MessageBodyWriter writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW(); Produces pm = writer.getClass().getAnnotation(Produces.class); if (pm != null) { List sorted = JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM); mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0); } } if (mt.isWildcardType() || mt.isWildcardSubtype()) { if ("application".equals(mt.getType()) || mt.isWildcardType()) { mt = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { throw ExceptionUtils.toNotAcceptableException(null, null); } } return mt; } private void setResponseDate(MultivaluedMap headers, boolean firstTry) { if (!firstTry || headers.containsKey(HttpHeaders.DATE)) { return; } SimpleDateFormat format = HttpUtils.getHttpDateFormat(); headers.putSingle(HttpHeaders.DATE, format.format(new Date())); } private boolean isResponseAlreadyHandled(Message m) { return isResponseAlreadyCommited(m) || isResponseRedirected(m); } private boolean isResponseAlreadyCommited(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.RESPONSE_COMMITED)); } private boolean isResponseRedirected(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.REQUEST_REDIRECTED)); } private void writeResponseToStream(OutputStream os, Object responseObj) { try { byte[] bytes = responseObj.toString().getBytes(StandardCharsets.UTF_8); os.write(bytes, 0, bytes.length); } catch (Exception ex) { LOG.severe("Problem with writing the data to the output stream"); ex.printStackTrace(); throw new RuntimeException(ex); } } private void setResponseStatus(Message message, int status) { message.put(Message.RESPONSE_CODE, status); boolean responseHeadersCopied = isResponseHeadersCopied(message); if (responseHeadersCopied) { HttpServletResponse response = (HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE); response.setStatus(status); } } // Some CXF interceptors such as FIStaxOutInterceptor will indirectly initiate // an early copying of response code and headers into the HttpServletResponse // TODO : Pushing the filter processing and copying response headers into say // PRE-LOGICAl and PREPARE_SEND interceptors will most likely be a good thing // however JAX-RS MessageBodyWriters are also allowed to add response headers // which is reason why a MultipartMap parameter in MessageBodyWriter.writeTo // method is modifiable. Thus we do need to know if the initial copy has already // occurred: for now we will just use to ensure the correct status is set private boolean isResponseHeadersCopied(Message message) { return PropertyUtils.isTrue(message.get(AbstractHTTPDestination.RESPONSE_HEADERS_COPIED)); } public void handleFault(Message message) { // complete } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13134 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java/#L73-L495 | 2 | 4824 | 13134 | minor |
| 2338 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 14167 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 2 | 2338 | 14167 | minor |
| 1652 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1652 | 11582 | minor |
| 672 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ContextMenuProvider extends MenuManager implements IMenuListener { private EditPartViewer viewer; /** * Constructs a context menu for the specified EditPartViewer. * * @param viewer * the editpart viewer */ public ContextMenuProvider(EditPartViewer viewer) { setViewer(viewer); addMenuListener(this); setRemoveAllWhenShown(true); } /** * Called when the menu is about to show. Subclasses must implement this * method to populate the menu each time it is shown. * * @param menu * this parameter is actually this object */ public abstract void buildContextMenu(IMenuManager menu); /** * Returns the EditPartViewer * * @return the viewer */ protected EditPartViewer getViewer() { return viewer; } /** * @see IMenuListener#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { buildContextMenu(menu); } /** * Sets the editpart viewer. Called during construction. * * @param viewer * the viewer */ protected void setViewer(EditPartViewer viewer) { this.viewer = viewer; } } |
data class | long method | t | t | f | long method | data class | 0 | 6563 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.gef/src/org/eclipse/gef/ContextMenuProvider.java/#L24-L76 | 1 | 672 | 6563 | minor |
| 4059 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } } |
blob | data class | t | t | f | data class | blob | 0 | 10711 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 | 1 | 4059 | 10711 | minor |
| 775 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3. Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4. Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5. Complex conditional logic (onInit() method has long and complex if/else logic) 6. Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7. Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8. Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9. Speculative generality (expectReply variable is not used for anything other than setting it to true or false) 10.Comments/dead code (setGenerateDestinationDirectory method is never used) 11.Magic numbers (destinationDirectoryFormat variable has a string value that is not explained or easily understood) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } } |
blob | Long method 2 Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3 Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4 Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5 Complex conditional logic (onInit() method has long and complex if/else logic) 6 Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7 Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8 Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9 Speculative generality (expectReply variable is not used for anything other than setting it to true or false) | t | f | f | . Long method 2. Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3. Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4. Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5. Complex conditional logic (onInit() method has long and complex if/else logic) 6. Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7. Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8. Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9. Speculative generality (expectReply variable is not used for anything other than setting it to true or false) | blob | 0 | 7352 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 | 2 | 775 | 7352 | minor |
| 425 | YES I found bad smells the bad smells are: 1.Long method, 2.Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } |
feature envy | Long method, 2Lazy class | t | f | f | .Long method, 2.Lazy class | feature envy | 0 | 4257 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L245-L247 | 2 | 425 | 4257 | minor |
| 1998 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | f | f | f | long method | 0 | 12702 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 2 | 1998 | 12702 | minor | ||
| 1671 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11636 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1671 | 11636 | minor |
| 3228 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 5328 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 | 1 | 3228 | 5328 | critical |
| 4081 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10762 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 4081 | 10762 | major |
| 670 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 6553 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 670 | 6553 | minor |
| 1498 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11127 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1498 | 11127 | minor |
| 2476 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Unnecessary comments 6. Use of Map instead of more specific data structure 7. Use of null checks 8. Lack of proper indentation and formatting 9. Inefficient algorithms 10. Inadequate variable names 11. Too many public methods 12. Code duplication in the constructors 13. Unnecessary conditional statements 14. Use of primitive types rather than more specific types 15. Missing usage of interfaces or abstract classes 16. Lack of error handling 17. Use of unnecessary data structures 18. Code complexity 19. Lack of clear documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
data class | Long method2 Feature envy3 Duplicate code 4 Inconsistent naming conventions 5 Unnecessary comments 6 Use of Map instead of more specific data structure 7 Use of null checks 8 Lack of proper indentation and formatting 9 Inefficient algorithms | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Inconsistent naming conventions 5. Unnecessary comments 6. Use of Map instead of more specific data structure 7. Use of null checks 8. Lack of proper indentation and formatting 9. Inefficient algorithms | data class | 0 | 14587 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 2 | 2476 | 14587 | minor |
| 107 | { "response": "YES I found bad smells", "bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Customer583Repository extends CrudRepository { List findByLastName(String lastName); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1412 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/repo/Customer583Repository.java/#L9-L12 | 2 | 107 | 1412 | critical |
| 618 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6205 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 1 | 618 | 6205 | minor |
| 5494 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | f | f | f | long method | 0 | 2683 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 1 | 5494 | 2683 | minor | ||
| 91 | {"response": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Controller public class SignupController { private final SignupHelper signupHelper; @Inject public SignupController(AccountRepository accountRepository, SignedUpGateway gateway) { this.signupHelper = new SignupHelper(accountRepository, gateway); } /** * Render a signup form to the person as HTML in their web browser. */ @RequestMapping(value="/signup", method=RequestMethod.GET) public SignupForm signupForm(WebRequest request) { Connection connection = ProviderSignInUtils.getConnection(request); if (connection != null) { request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Greenhouse account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST); return SignupForm.fromProviderUser(connection.fetchUserProfile()); } else { return new SignupForm(); } } /** * Process a signup form submission. * Delegate to a {@link SignupHelper} to actually complete the signin transaction. * Redirects the new member to the application home page on successful sign-in. */ @RequestMapping(value="/signup", method=RequestMethod.POST) public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) { if (formBinding.hasErrors()) { return null; } boolean result = signupHelper.signup(form, formBinding, new SignupCallback() { public void postSignup(Account account) { ProviderSignInUtils.handlePostSignUp(account.getId().toString(), request); } }); return result ? "redirect:/" : null; } @RequestMapping(value="/signup", method=RequestMethod.POST, consumes="application/json") public ResponseEntity> signupFromApi(@RequestBody SignupForm form) { BindingResult formBinding = validate(form); // Temporary manual validation until SPR-9826 is fixed. if (formBinding.hasErrors()) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Validation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } boolean result = signupHelper.signup(form, formBinding); if (result) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account created"); return new ResponseEntity>(errorResponse, HttpStatus.CREATED); } else { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account creation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } } private BindException validate(SignupForm form) { BindException errors; errors = new BindException(form, "signupForm"); LazyValidatorFactory lvf = new LazyValidatorFactory(); Validator validator = new SpringValidatorAdapter(lvf.getValidator()); ValidationUtils.invokeValidator(validator, form, errors); return errors; } private List> getErrorsMap(BindingResult formBinding) { List fieldErrors = formBinding.getFieldErrors(); List> errors = new ArrayList>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map fieldErrorMap = new HashMap(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap); } return errors; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1242 | https://github.com/spring-projects/greenhouse/blob/c7994183812150de971ef4a76c08d5b4631ab5d1/src/main/java/com/springsource/greenhouse/signup/SignupController.java/#L54-L143 | 2 | 91 | 1242 | minor |
| 1649 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11566 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 | 2 | 1649 | 11566 | critical |
| 1920 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12413 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1920 | 12413 | minor |
| 5268 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Scanner { private final List tokens; private int currentPosition = 0; public Scanner(final List tokens) { this.tokens = tokens; } public NodeSelect scan() { return scanSelect(); } public void checkTail() { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && (item1.getNodeType() != NodeType.OPERATION || item1.getValue().length() != 0)) { currentPosition = num1; throwSyntaxError(SyntaxError.EXPECTING_END_OF_STRING); } } private NodeSelect scanSelect() { final Node node1 = ensureToken(NodeType.NAME, "select", SyntaxError.EXPECTING_SELECT); //$NON-NLS-1$ final NodeSelect select1 = new NodeSelect(); if (scanToken(NodeType.OPERATION, "*") != null) //$NON-NLS-1$ { select1.setFields(null); } else { select1.setFields(scanFieldNameList(false, NodeType.FIELD_LIST)); } while (true) { if (scanToken(NodeType.NAME, "from") != null) //$NON-NLS-1$ { if (select1.getFrom() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_FROM); } select1.setFrom(scanTableName()); continue; } if (scanToken(NodeType.NAME, "where") != null) //$NON-NLS-1$ { if (select1.getWhere() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_WHERE); } select1.setWhere(scanWhere(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getGroupBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_GROUP_BY); } select1.setGroupBy(scanFieldNameList(false, NodeType.GROUP_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "order") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getOrderBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_ORDER_BY); } select1.setOrderBy(scanFieldNameList(true, NodeType.ORDER_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "asof") != null) //$NON-NLS-1$ { if (select1.getAsOf() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_AS_OF); } select1.setAsOf(scanValue(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "mode") != null) //$NON-NLS-1$ { if (select1.getMode() != null) { currentPosition--; throwSyntaxError(SyntaxError.DUPLICATE_MODE); } select1.setMode(ScanMode()); continue; } select1.setStartOffset(node1.getStartOffset()); select1.setEndOffset(((NodeItem) tokens.get(tokens.size() - 1)).getEndOffset()); return select1; } } private Node scanWhere(final NodeTableName table) { return scanCondition4(table); } private Node scanCondition4(final NodeTableName table) { Node node1 = scanCondition3(table); NodeOrOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "or"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "||"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeOrOperator(); operator1.add(node1); } operator1.add(scanCondition3(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition3(final NodeTableName table) { Node node1 = scanCondition2(table); NodeAndOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "and"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "&&"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeAndOperator(); operator1.add(node1); } operator1.add(scanCondition2(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition2(final NodeTableName table) { Node node1 = scanToken(NodeType.NAME, "not"); //$NON-NLS-1$ if (node1 == null) { node1 = scanToken(NodeType.OPERATION, "!"); //$NON-NLS-1$ } if (node1 != null) { final Node node2 = scanCondition2(table); final Node node3 = new NodeNotOperator(node2); node3.setStartOffset(node1.getStartOffset()); node3.setEndOffset(node2.getEndOffset()); return node3; } node1 = scanToken(NodeType.NAME, "ever"); //$NON-NLS-1$ if (node1 != null) { final Node node4 = scanCondition2(table); final Node node5 = new NodeEverOperator(node4); node5.setStartOffset(node1.getStartOffset()); node5.setEndOffset(node4.getEndOffset()); return node5; } node1 = scanToken(NodeType.NAME, "never"); //$NON-NLS-1$ if (node1 != null) { final Node node6 = scanCondition2(table); final Node node7 = new NodeNotOperator(new NodeEverOperator(node6)); node7.setStartOffset(node1.getStartOffset()); node7.setEndOffset(node6.getEndOffset()); return node7; } return scanCondition1(table); } private Node scanCondition1(final NodeTableName table) { final Node node1 = scanToken(NodeType.OPERATION, "("); //$NON-NLS-1$ if (node1 != null) { final Node node2 = scanWhere(table); final Node node3 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ node2.setStartOffset(node1.getStartOffset()); node2.setEndOffset(node3.getEndOffset()); node2.setHasParantheses(true); return node2; } final NodeCondition condition1 = new NodeCondition(); Node node4 = condition1; condition1.setLeft(scanFieldName(table)); final Stack stack1 = new Stack(); while (true) { if (scanToken(NodeType.NAME, "not") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); continue; } if (scanToken(NodeType.NAME, "ever") != null) //$NON-NLS-1$ { stack1.push(NodeType.EVER); continue; } if (scanToken(NodeType.NAME, "never") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); stack1.push(NodeType.EVER); continue; } break; } while (true) { if (stack1.size() <= 0) { condition1.setCondition(scanConditionOperator(node4 != condition1)); if (condition1.getCondition() == Condition.NONE) { throwSyntaxError(SyntaxError.EXPECTING_COMPARISON_OPERATOR); } if (condition1.getCondition() == Condition.GROUP) { condition1.setRight(scanValue(table)); } else if (condition1.getCondition() == Condition.IN) { final Node node5 = ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final Node node6 = scanValueList(table); final Node node7 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ node6.setStartOffset(node5.getStartOffset()); node6.setEndOffset(node7.getEndOffset()); condition1.setRight(node6); } else if (condition1.getCondition() == Condition.UNDER) { condition1.setRight(scanValue(table)); } else { Node node8 = TryScanFieldName(); if (node8 == null) { node8 = TryScanExpression(); } if (node8 != null) { condition1.setRight(node8); } else { throwSyntaxError(SyntaxError.EXPECTING_FIELD_OR_EXPRESSION); } } node4.setStartOffset(condition1.getLeft().getStartOffset()); node4.setEndOffset(condition1.getRight().getEndOffset()); return node4; } final NodeType nodeType = stack1.pop(); if (nodeType == NodeType.NOT) { node4 = new NodeNotOperator(node4); } else if (nodeType == NodeType.EVER) { node4 = new NodeEverOperator(node4); } } } private Node scanValueList(final NodeTableName table) { final NodeValueList list1 = new NodeValueList(); do { list1.add(scanExpression(table)); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ list1.setStartOffset(list1.getItem(0).getStartOffset()); list1.setEndOffset(list1.getItem(list1.getCount() - 1).getEndOffset()); return list1; } private Node scanValue(final NodeTableName table) { final Node node = TryScanSingleValue(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); } return node; } private Node scanExpression(final NodeTableName nodeTable) { final Node node = TryScanExpression(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); return null; } return node; } private Condition scanConditionOperator(final boolean afterNotOrEver) { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && ((item1.getNodeType() == NodeType.NAME) || ((item1.getNodeType() == NodeType.OPERATION) && !afterNotOrEver))) { Condition condition1 = ConditionalOperators.find(item1.getValue()); if (condition1 == Condition.IN && scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { condition1 = Condition.GROUP; } else if (condition1 == Condition.CONTAINS && scanToken(NodeType.NAME, "words") != null) //$NON-NLS-1$ { condition1 = Condition.CONTAINS_WORDS; } if (condition1 != Condition.NONE) { return condition1; } } currentPosition = num1; if (!afterNotOrEver) { return Condition.NONE; } return Condition.EQUALS; } private NodeTableName scanTableName() { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == NodeType.NAME) { return new NodeTableName((NodeName) tokenNode); } currentPosition = savedCurrentPosition; throwSyntaxError(SyntaxError.EXPECTING_TABLE_NAME); return null; } // direction is true if each field name in the field name list can be // suffixed by an optional // direction indicator - asc or desc private NodeFieldList scanFieldNameList(final boolean direction, final NodeType nodeType) { final NodeFieldList fieldListNode = new NodeFieldList(nodeType); while (true) { final NodeFieldName fieldNameNode = scanFieldName(null); if (direction) { if (scanToken(NodeType.NAME, "asc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.ASCENDING); } else if (scanToken(NodeType.NAME, "desc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.DESCENDING); } } fieldListNode.add(fieldNameNode); /* * if the next token is not a comma operator, then the field list is * finished */ if (scanToken(NodeType.OPERATION, ",") == null) //$NON-NLS-1$ { if (fieldListNode.getCount() != 0) { /* * if the field list node is not empty, set it's start and * end offset by using the starting and ending node in the * list */ fieldListNode.setStartOffset(fieldListNode.getItem(0).getStartOffset()); fieldListNode.setEndOffset(fieldListNode.getItem(fieldListNode.getCount() - 1).getEndOffset()); } return fieldListNode; } } } private NodeFieldName scanFieldName(final NodeTableName table) { final Node node = TryScanFieldName(); if (node != null) { return (NodeFieldName) node; } throwSyntaxError(SyntaxError.EXPECTING_FIELD_NAME); return null; } private NodeMode ScanMode() { ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final NodeMode mode = new NodeMode(); do { final int pos = currentPosition; final NodeItem item = nextToken(); if ((item == null) || !(item.getNodeType().equals(NodeType.NAME))) { currentPosition = pos; throwSyntaxError(SyntaxError.EXPECTING_MODE); return null; } mode.add(item); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ mode.setStartOffset(mode.getItem(0).getStartOffset()); mode.setEndOffset(mode.getItem(mode.getCount() - 1).getEndOffset()); return mode; } private NodeItem ensureToken(final NodeType type, final String str, final SyntaxError syntaxError) { final NodeItem tokenNode = scanToken(type, str); if (tokenNode == null) { throwSyntaxError(syntaxError); } return tokenNode; } private void throwSyntaxError(final SyntaxError error) { NodeItem causeNode = null; if (currentPosition < tokens.size()) { causeNode = (NodeItem) tokens.get(currentPosition); } throw new SyntaxException(causeNode, error); } private NodeItem scanToken(final NodeType type, final String str) { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == type && str.equalsIgnoreCase(tokenNode.getValue())) { return tokenNode; } currentPosition = savedCurrentPosition; return null; } private NodeItem nextToken() { if (currentPosition < tokens.size()) { return (NodeItem) tokens.get(currentPosition++); } return null; } private Node TryScanExpression() { int num; Node node = TryScanSingleValue(); if (node == null) { return null; } while (true) { num = currentPosition; final NodeItem item = nextToken(); if (item != null) { Arithmetic none = Arithmetic.NONE; Node node2 = null; if (item.getNodeType() == NodeType.NUMBER) { none = ArithmeticalOperators.find(item.getValue().substring(0, 1)); if (none != Arithmetic.NONE) { item.setValue(item.getValue().substring(1)); node2 = item; } } else if (item.getNodeType() == NodeType.OPERATION) { none = ArithmeticalOperators.find(item.getValue()); if (none != Arithmetic.NONE) { node2 = TryScanSingleValue(); } } if ((none != Arithmetic.NONE) && (node2 != null)) { final NodeArithmetic arithmetic2 = new NodeArithmetic(); arithmetic2.setArithmetic(none); arithmetic2.setLeft(node); arithmetic2.setRight(node2); arithmetic2.setStartOffset(arithmetic2.getLeft().getStartOffset()); arithmetic2.setEndOffset(arithmetic2.getRight().getEndOffset()); node = arithmetic2; continue; } } currentPosition = num; return node; } } private Node TryScanFieldName() { Node node = null; final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (node2.getNodeType() == NodeType.NAME)) { final NodeItem item = scanToken(NodeType.OPERATION, "."); //$NON-NLS-1$ Node node3 = null; if (item != null) { node3 = nextToken(); if ((node3 != null) && (node3.getNodeType() == NodeType.NAME)) { node = new NodeFieldName((NodeName) node2, (NodeName) node3); } } else { node = new NodeFieldName((NodeName) node2); } } if (node == null) { currentPosition = pos; return null; } return node; } private Node TryScanSingleValue() { final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (((node2.getNodeType() == NodeType.NUMBER) || (node2.getNodeType() == NodeType.STRING)) || ((node2.getNodeType() == NodeType.VARIABLE) || (node2.getNodeType() == NodeType.BOOL_VALUE)))) { return node2; } currentPosition = pos; return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14729 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/workitem/internal/wiqlparse/Scanner.java/#L9-L514 | 1 | 5268 | 14729 | minor |
| 391 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method | t | t | f | long method | data class | 0 | 3964 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 391 | 3964 | major |
| 1914 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 12403 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 1914 | 12403 | minor |
| 3145 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4282 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 3145 | 4282 | major |
| 1054 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { // @formatter:off @Override protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages .simpMessageDestMatchers("/queue/**", "/topic/**").denyAll() .simpSubscribeDestMatchers("/queue/**/*-user*", "/topic/**/*-user*").denyAll() .anyMessage().authenticated(); } // @formatter:on } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9489 | https://github.com/spring-projects/spring-session/blob/a5a3bc5d0b57d396882199dfbf8cb560a355ca1e/samples/boot/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java/#L26-L39 | 2 | 1054 | 9489 | minor |
| 2086 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13101 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 1 | 2086 | 13101 | major |
| 2330 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14150 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 2330 | 14150 | minor |
| 686 | YES I found bad smells The bad smells are: 1. Feature Envy 2. Duplicate Code 3. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Parser { public static GetOrderReferenceDetailsResponseData getOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final GetOrderReferenceDetailsResponse response = marshalXML(GetOrderReferenceDetailsResponse.class, rawResponse); return new GetOrderReferenceDetailsResponseData(response, rawResponse); } public static SetOrderReferenceDetailsResponseData setOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final SetOrderReferenceDetailsResponse response = marshalXML(SetOrderReferenceDetailsResponse.class, rawResponse); return new SetOrderReferenceDetailsResponseData(response, rawResponse); } public static AuthorizeResponseData getAuthorizeData(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeResponse response = marshalXML(AuthorizeResponse.class, rawResponse); return new AuthorizeResponseData(response, rawResponse); } public static GetAuthorizationDetailsResponseData getAuthorizationDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetAuthorizationDetailsResponse response = marshalXML(GetAuthorizationDetailsResponse.class, rawResponse); return new GetAuthorizationDetailsResponseData(response, rawResponse); } public static CaptureResponseData getCapture(ResponseData rawResponse) throws AmazonServiceException { final CaptureResponse response = marshalXML(CaptureResponse.class, rawResponse); return new CaptureResponseData(response, rawResponse); } public static GetCaptureDetailsResponseData getCaptureDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetCaptureDetailsResponse response = marshalXML(GetCaptureDetailsResponse.class, rawResponse); return new GetCaptureDetailsResponseData(response, rawResponse); } public static ConfirmOrderReferenceResponseData confirmOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ConfirmOrderReferenceResponse response = marshalXML(ConfirmOrderReferenceResponse.class, rawResponse); return new ConfirmOrderReferenceResponseData(response, rawResponse); } public static CloseAuthorizationResponseData closeAuthorizationResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseAuthorizationResponse response = marshalXML(CloseAuthorizationResponse.class, rawResponse); return new CloseAuthorizationResponseData(response, rawResponse); } public static CancelOrderReferenceResponseData getCancelOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CancelOrderReferenceResponse response = marshalXML(CancelOrderReferenceResponse.class, rawResponse); return new CancelOrderReferenceResponseData(response, rawResponse); } public static CloseOrderReferenceResponseData getCloseOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CloseOrderReferenceResponse response = marshalXML(CloseOrderReferenceResponse.class, rawResponse); return new CloseOrderReferenceResponseData(response, rawResponse); } public static RefundResponseData getRefundData(ResponseData rawResponse) throws AmazonServiceException { final RefundResponse response = marshalXML(RefundResponse.class, rawResponse); return new RefundResponseData(response, rawResponse); } public static GetRefundDetailsResponseData getRefundDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetRefundDetailsResponse response = marshalXML(GetRefundDetailsResponse.class, rawResponse); return new GetRefundDetailsResponseData(response, rawResponse); } public static GetBillingAgreementDetailsResponseData getBillingAgreementDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetBillingAgreementDetailsResponse response = marshalXML(GetBillingAgreementDetailsResponse.class, rawResponse); return new GetBillingAgreementDetailsResponseData(response, rawResponse); } public static SetBillingAgreementDetailsResponseData getSetBillingAgreementDetailsResponse(ResponseData rawResponse) throws AmazonServiceException { final SetBillingAgreementDetailsResponse response = marshalXML(SetBillingAgreementDetailsResponse.class, rawResponse); return new SetBillingAgreementDetailsResponseData(response, rawResponse); } public static ValidateBillingAgreementResponseData getValidateBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ValidateBillingAgreementResponse response = marshalXML(ValidateBillingAgreementResponse.class, rawResponse); return new ValidateBillingAgreementResponseData(response, rawResponse); } public static ConfirmBillingAgreementResponseData confirmBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ConfirmBillingAgreementResponse response = marshalXML(ConfirmBillingAgreementResponse.class, rawResponse); return new ConfirmBillingAgreementResponseData(response, rawResponse); } public static AuthorizeOnBillingAgreementResponseData getAuthorizeOnBillingAgreement(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeOnBillingAgreementResponse response = marshalXML(AuthorizeOnBillingAgreementResponse.class, rawResponse); return new AuthorizeOnBillingAgreementResponseData(response, rawResponse); } public static CloseBillingAgreementResponseData closeBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseBillingAgreementResponse response = marshalXML(CloseBillingAgreementResponse.class, rawResponse); return new CloseBillingAgreementResponseData(response, rawResponse); } public static GetProviderCreditDetailsResponseData getGetProviderCreditDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditDetailsResponse response = marshalXML(GetProviderCreditDetailsResponse.class, rawResponse); return new GetProviderCreditDetailsResponseData(response, rawResponse); } public static GetProviderCreditReversalDetailsResponseData getProviderCreditReversalDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditReversalDetailsResponse response = marshalXML(GetProviderCreditReversalDetailsResponse.class, rawResponse); return new GetProviderCreditReversalDetailsResponseData(response, rawResponse); } public static ReverseProviderCreditResponseData getReverseProviderCreditResponseData(ResponseData rawResponse) throws AmazonServiceException { final ReverseProviderCreditResponse response = marshalXML(ReverseProviderCreditResponse.class, rawResponse); return new ReverseProviderCreditResponseData(response, rawResponse); } public static GetServiceStatusResponseData getServiceStatus( ResponseData rawResponse) throws AmazonServiceException { final GetServiceStatusResponse response = marshalXML( GetServiceStatusResponse.class, rawResponse); return new GetServiceStatusResponseData(response, rawResponse); } public static CreateOrderReferenceForIdResponseData createOrderReferenceForId( ResponseData rawResponse) throws AmazonServiceException { final CreateOrderReferenceForIdResponse response = marshalXML( CreateOrderReferenceForIdResponse.class, rawResponse); return new CreateOrderReferenceForIdResponseData(response, rawResponse); } public static ListOrderReferenceResponseData listOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceResponse response = marshalXML(ListOrderReferenceResponse.class, rawResponse); return new ListOrderReferenceResponseData(response, rawResponse); } public static ListOrderReferenceByNextTokenResponseData listOrderReferenceByNextToken(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceByNextTokenResponse response = marshalXML(ListOrderReferenceByNextTokenResponse.class, rawResponse); return new ListOrderReferenceByNextTokenResponseData(response, rawResponse); } public static SetOrderAttributesResponseData setOrderAttributes(ResponseData rawResponse) throws AmazonServiceException { final SetOrderAttributesResponse response = marshalXML(SetOrderAttributesResponse.class, rawResponse); return new SetOrderAttributesResponseData(response, rawResponse); } public static GetMerchantAccountStatusResponseData getMerchantAccountStatus(ResponseData rawResponse) throws AmazonServiceException { final GetMerchantAccountStatusResponse response = marshalXML(GetMerchantAccountStatusResponse.class, rawResponse); return new GetMerchantAccountStatusResponseData(response, rawResponse); } public static T marshalXML(Class clazz, ResponseData rawResponse) throws AmazonServiceException { try { if (rawResponse.getStatusCode() == 200) { T responseObject = null; final JAXBContext context = JAXBContext.newInstance(clazz); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); responseObject = (T) unmarshaller.unmarshal(xmlStreamReader); return responseObject; } else { generateErrorException(rawResponse); } } catch (JAXBException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } return null; } public static void generateErrorException(ResponseData rawResponse) throws AmazonServiceException, JAXBException { final JAXBContext context = JAXBContext.newInstance(ErrorResponse.class); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); try { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); final ErrorResponse result = (ErrorResponse) unmarshaller.unmarshal(xmlStreamReader); throw new AmazonServiceException(result, rawResponse); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } } } |
blob | Feature Envy 2 Duplicate Code 3 Long Method | t | f | f | . Feature Envy 2. Duplicate Code 3. Long Method | blob | 0 | 6625 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/parser/Parser.java/#L57-L252 | 2 | 686 | 6625 | major |
| 2187 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13438 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2187 | 13438 | minor |
| 1307 | Yes, I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | Feature envy | t | f | f | . Feature envy | blob | 0 | 10676 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 2 | 1307 | 10676 | minor |
| 4965 | {"answer": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 13592 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 1 | 4965 | 13592 | minor |
| 27 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 704 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 1 | 27 | 704 | major |
| 1650 | { "output": "YES I found bad smells. the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | t | f | f | data class | 0 | 11573 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 1 | 1650 | 11573 | minor | ||
| 5391 | { "message": "Please share the Java code for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | Not specified | f | f | f | false | 0 | 15152 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 5391 | 15152 | minor | |
| 2577 | YES I found bad smells #1. Long method #2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | Long method#2 Feature envy | t | f | f | . Long method#2. Feature envy | data class | 0 | 14935 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 2 | 2577 | 14935 | minor |
| 3820 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Inappropriate naming conventions, 5. Poor code structure, 6. Inconsistent coding style, 7. Lack of comments/documentation, 8. Lack of error handling, 9. Unnecessary use of Lists.newLinkedList(), 10. Overly complex logic, 11. Use of StringBuffer instead of StringBuilder. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GlobbingPathHelper { /** * Converts the provided path containing glob characters * * and ** into a regular expression. The definition matches * that of the GlobbingPathFilter with the addition that this conversion * also supports sub-paths which do not start with a /. * * The rules are: * * leading ** matches /foo and bar * leading /** matches /foo but not bar * intermittent ** matches zero or any number of path elements * trailing ** matches anything not ending with a / * single * matches anything except / * ? is not a special character * anything not a star is wrapped into \Q...\E pairs * * @param pathWithGlobs path that can contain * and ** * @return a regular expression * @see GlobbingPathFilter */ public static String globPathAsRegex(String pathWithGlobs) { if (pathWithGlobs == null) { return null; } else if (!pathWithGlobs.contains("*")) { return pathWithGlobs; } List elements = Lists.newLinkedList(elements(pathWithGlobs)); StringBuffer sb = new StringBuffer(); sb.append("\\Q"); if (pathWithGlobs.startsWith("/")) { sb.append("/"); } if (elements.get(0).equals("**")) { sb.append("\\E[^/]*(/[^/]*)*\\Q"); elements.remove(0); } int size = elements.size(); boolean endsWithStarStar = size == 0 ? false : elements.get(size - 1).equals("**"); if (endsWithStarStar) { elements.remove(size - 1); } boolean addSlash = false; for(int i=0; i<elements.size(); i++) { String pathElem = elements.get(i); if (addSlash) { sb.append("/"); } if (pathElem.equals("**")) { addSlash = false; sb.append("\\E([^/]*/)*\\Q"); } else { sb.append(pathElem.replace("*", "\\E[^/]*\\Q")); addSlash = true; } } if (endsWithStarStar) { sb.append("\\E(/[^/]*)*"); } else if (pathWithGlobs.endsWith("/")) { sb.append("/\\E"); } else { sb.append("\\E"); } return sb.toString(); } } |
blob | Long method, 2 Feature envy, 3 Magic numbers, 4 Inappropriate naming conventions, 5 Poor code structure, 6 Inconsistent coding style, 7 Lack of comments/documentation, 8 Lack of error handling, 9 Unnecessary use of ListsnewLinkedList(), | t | f | f | . Long method, 2. Feature envy, 3. Magic numbers, 4. Inappropriate naming conventions, 5. Poor code structure, 6. Inconsistent coding style, 7. Lack of comments/documentation, 8. Lack of error handling, 9. Unnecessary use of Lists.newLinkedList(), | blob | 0 | 9761 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/observation/filter/GlobbingPathHelper.java/#L27-L94 | 2 | 3820 | 9761 | minor |
| 2229 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | long method | t | t | f | long method | blob | 0 | 13583 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 2229 | 13583 | minor |
| 819 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Primitive obsession", "Feature envy", "Long parameter list", "Data clumps", "Data class", "Duplicate code", "Inappropriate intimacy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } } |
blob | long method, primitive obsession, feature envy, long parameter list, data clumps, data class, duplicate code, inappropriate intimacy | t | t | f | long method, primitive obsession, feature envy, long parameter list, data clumps, data class, duplicate code, inappropriate intimacy | blob | 0 | 7677 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 | 2 | 819 | 7677 | critical |
| 854 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
blob | data class | t | t | f | data class | blob | 0 | 7878 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 854 | 7878 | minor |
| 1120 | {"message": "YES I found bad smells: the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9974 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 1 | 1120 | 9974 | minor |
| 228 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | long method | t | t | f | long method | data class | 0 | 2451 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 1 | 228 | 2451 | minor |
| 2872 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | long method | t | t | f | long method | feature envy | 0 | 2003 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 1 | 2872 | 2003 | minor |
| 367 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 3757 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 367 | 3757 | major |
| 860 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number for timeout values 3. Log statements used for debugging instead of using a proper debugger 4. Overly complex and nested try-catch blocks 5. Dead code - unused variables and parameters 6. Method with too many parameters 7. Feature envy - CommunicateAction class accessing ConnectionLoadBalanceServer's variables directly 8. Lack of proper error handling and handling of Exceptions 9. Multiple responsibilities - ConnectionLoadBalanceServer class handles both server setup and communication actions, should be split into separate classes 10. Repetitive code within start() and stop() methods 11. Use of volatile and synchronized modifiers without clear justification or understanding of proper usage 12. Lack of proper encapsulation and abstraction 13. Potential for race conditions and thread-safety issues 14. Poor naming conventions for variables and methods 15. Poorly structured and organized code with no clear separation of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConnectionLoadBalanceServer { private static final Logger logger = LoggerFactory.getLogger(ConnectionLoadBalanceServer.class); private final String hostname; private final int port; private final SSLContext sslContext; private final ExecutorService threadPool; private final LoadBalanceProtocol loadBalanceProtocol; private final int connectionTimeoutMillis; private final int numThreads; private final EventReporter eventReporter; private volatile Set communicationActions = Collections.emptySet(); private final BlockingQueue connectionQueue = new LinkedBlockingQueue<>(); private volatile AcceptConnection acceptConnection; private volatile ServerSocket serverSocket; private volatile boolean stopped = true; public ConnectionLoadBalanceServer(final String hostname, final int port, final SSLContext sslContext, final int numThreads, final LoadBalanceProtocol loadBalanceProtocol, final EventReporter eventReporter, final int connectionTimeoutMillis) { this.hostname = hostname; this.port = port; this.sslContext = sslContext; this.loadBalanceProtocol = loadBalanceProtocol; this.connectionTimeoutMillis = connectionTimeoutMillis; this.numThreads = numThreads; this.eventReporter = eventReporter; threadPool = new FlowEngine(numThreads, "Load Balance Server"); } public void start() throws IOException { if (!stopped) { return; } stopped = false; if (serverSocket != null) { return; } try { serverSocket = createServerSocket(); } catch (final Exception e) { throw new IOException("Could not begin listening for incoming connections in order to load balance data across the cluster. Please verify the values of the " + "'nifi.cluster.load.balance.port' and 'nifi.cluster.load.balance.host' properties as well as the 'nifi.security.*' properties", e); } final Set actions = new HashSet<>(numThreads); for (int i=0; i < numThreads; i++) { final CommunicateAction action = new CommunicateAction(loadBalanceProtocol); actions.add(action); threadPool.submit(action); } this.communicationActions = actions; acceptConnection = new AcceptConnection(serverSocket); final Thread receiveConnectionThread = new Thread(acceptConnection); receiveConnectionThread.setName("Receive Queue Load-Balancing Connections"); receiveConnectionThread.start(); } public int getPort() { return serverSocket.getLocalPort(); } public void stop() { stopped = false; threadPool.shutdown(); if (acceptConnection != null) { acceptConnection.stop(); } communicationActions.forEach(CommunicateAction::stop); Socket socket; while ((socket = connectionQueue.poll()) != null) { try { socket.close(); logger.info("{} Closed connection to {} on Server stop", this, socket.getRemoteSocketAddress()); } catch (final IOException ioe) { logger.warn("Failed to properly close socket to " + socket.getRemoteSocketAddress(), ioe); } } } private ServerSocket createServerSocket() throws IOException { final InetAddress inetAddress = hostname == null ? null : InetAddress.getByName(hostname); if (sslContext == null) { return new ServerSocket(port, 50, InetAddress.getByName(hostname)); } else { final ServerSocket serverSocket = sslContext.getServerSocketFactory().createServerSocket(port, 50, inetAddress); ((SSLServerSocket) serverSocket).setNeedClientAuth(true); return serverSocket; } } private class CommunicateAction implements Runnable { private final LoadBalanceProtocol loadBalanceProtocol; private volatile boolean stopped = false; public CommunicateAction(final LoadBalanceProtocol loadBalanceProtocol) { this.loadBalanceProtocol = loadBalanceProtocol; } public void stop() { this.stopped = true; } @Override public void run() { String peerDescription = ""; while (!stopped) { Socket socket = null; try { socket = connectionQueue.poll(1, TimeUnit.SECONDS); if (socket == null) { continue; } peerDescription = socket.getRemoteSocketAddress().toString(); if (socket.isClosed()) { logger.debug("Connection to Peer {} is closed. Will not attempt to communicate over this Socket.", peerDescription); continue; } logger.debug("Receiving FlowFiles from Peer {}", peerDescription); loadBalanceProtocol.receiveFlowFiles(socket); if (socket.isConnected()) { logger.debug("Finished receiving FlowFiles from Peer {}. Will recycle connection.", peerDescription); connectionQueue.offer(socket); } else { logger.debug("Finished receiving FlowFiles from Peer {}. Socket is no longer connected so will not recycle connection.", peerDescription); } } catch (final Exception e) { if (socket != null) { try { socket.close(); } catch (final IOException ioe) { e.addSuppressed(ioe); } } logger.error("Failed to communicate with Peer {}", peerDescription, e); eventReporter.reportEvent(Severity.ERROR, "Load Balanced Connection", "Failed to receive FlowFiles for Load Balancing due to " + e); } } logger.info("Connection Load Balance Server shutdown. Will no longer handle incoming requests."); } } private class AcceptConnection implements Runnable { private final ServerSocket serverSocket; private volatile boolean stopped = false; public AcceptConnection(final ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void stop() { stopped = true; } @Override public void run() { try { serverSocket.setSoTimeout(1000); } catch (final Exception e) { logger.error("Failed to set soTimeout on Server Socket for Load Balancing data across cluster", e); } while (!stopped) { try { final Socket socket; try { socket = serverSocket.accept(); } catch (final SocketTimeoutException ste) { continue; } socket.setSoTimeout(connectionTimeoutMillis); connectionQueue.offer(socket); } catch (final Exception e) { logger.error("{} Failed to accept connection from other node in cluster", ConnectionLoadBalanceServer.this, e); } } try { serverSocket.close(); } catch (final Exception e) { logger.warn("Failed to properly shutdown Server Socket for Load Balancing", e); } } } @Override public String toString() { return "ConnectionLoadBalanceServer[hostname=" + hostname + ", port=" + port + ", secure=" + (sslContext != null) + "]"; } } |
blob | Long method2 Magic number for timeout values3 Log statements used for debugging instead of using a proper debugger4 Overly complex and nested try-catch blocks5 Dead code - unused variables and parameters6 Method with too many parameters7 Feature envy - CommunicateAction class accessing ConnectionLoadBalanceServer's variables directly8 Lack of proper error handling and handling of Exceptions 9 Multiple responsibilities - ConnectionLoadBalanceServer class handles both server setup and communication actions, should be split into separate classes | t | f | f | . Long method2. Magic number for timeout values3. Log statements used for debugging instead of using a proper debugger4. Overly complex and nested try-catch blocks5. Dead code - unused variables and parameters6. Method with too many parameters7. Feature envy - CommunicateAction class accessing ConnectionLoadBalanceServer's variables directly8. Lack of proper error handling and handling of Exceptions 9. Multiple responsibilities - ConnectionLoadBalanceServer class handles both server setup and communication actions, should be split into separate classes | blob | 0 | 7901 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/clustered/server/ConnectionLoadBalanceServer.java/#L42-L251 | 2 | 860 | 7901 | major |
| 29 | {"message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 714 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 2 | 29 | 714 | minor |
| 260 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2825 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 2 | 260 | 2825 | minor |
| 133 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotPage extends ContactsDisplayPage { @SpringBean private ContactDao dao; @Override protected ContactDataProvider getDataProvider() { return new ProxyDataProvider(dao); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1634 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-examples/src/main/java/org/apache/wicket/examples/spring/annot/web/AnnotPage.java/#L27-L37 | 2 | 133 | 1634 | minor |
| 3889 | { "message": "YES I found bad smells", "bad_smells": [ {"1": "Long Method"} ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 10168 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 1 | 3889 | 10168 | critical |
| 1067 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | long method | t | t | f | long method | data class | 0 | 9582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1067 | 9582 | minor |
| 2630 | YES, I found bad smells. The bad smells are: 1. Long method (AllocationManager) 2. Primitive obsession (AtomicLong, int) 3. Inappropriate intimacy (AllocationManager has direct access to BufferLedger) 4. Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator) 5. Inappropriate coupling (AllocationManager knows details about BufferLedger class) 6. Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes) 7. Data class (BufferLedger contains only getters and setters) 8. No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes) 9. Excessive commenting (explanation in comments is not always necessary) 10. No error handling for invalid inputs (e.g. in associate method) 11. Feature envy (BufferLedger has knowledge about AllocationManager's internals) 12. Magic numbers (values like 0 and 1 should be declared as constants) 13. Inappropriate visibility (BufferLedger has public inner class, should be private) 14. Inconsistent use of unit of time (nanoseconds and milliseconds are mixed) 15. Poor exception handling (some methods catch exceptions but do nothing with them) 16. Code duplication (similar code in associate method and transferBalance method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | Long method (AllocationManager)2 Primitive obsession (AtomicLong, int)3 Inappropriate intimacy (AllocationManager has direct access to BufferLedger)4 Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator)5 Inappropriate coupling (AllocationManager knows details about BufferLedger class)6 Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes)7 Data class (BufferLedger contains only getters and setters)8 No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes)9 Excessive commenting (explanation in comments is not always necessary) | t | f | f | . Long method (AllocationManager)2. Primitive obsession (AtomicLong, int)3. Inappropriate intimacy (AllocationManager has direct access to BufferLedger)4. Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator)5. Inappropriate coupling (AllocationManager knows details about BufferLedger class)6. Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes)7. Data class (BufferLedger contains only getters and setters)8. No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes)9. Excessive commenting (explanation in comments is not always necessary) | blob | 0 | 15098 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 2 | 2630 | 15098 | minor |
| 973 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Not specified | f | f | f | false | 0 | 8773 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 973 | 8773 | minor | |
| 2281 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13809 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 2281 | 13809 | major |
| 1865 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12235 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 1 | 1865 | 12235 | major |
| 1450 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10993 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 2 | 1450 | 10993 | minor |
| 593 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GwtDeviceServiceImpl extends KapuaRemoteServiceServlet implements GwtDeviceService { private static final long serialVersionUID = -1391026997499175151L; private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private boolean isSameId; @Override public GwtDevice findDevice(String scopeIdString, String deviceIdString) throws GwtKapuaException { GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = deviceRegistryService.find(scopeId, deviceId); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public ListLoadResult findDeviceProfile(String scopeIdString, String deviceIdString) throws GwtKapuaException { List pairs = new ArrayList(); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceEventService deviceEventService = locator.getService(DeviceEventService.class); final DeviceConnectionService deviceConnectionService = locator.getService(DeviceConnectionService.class); GroupService groupService = locator.getService(GroupService.class); final UserService userService = locator.getService(UserService.class); try { final KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); final Device device = deviceRegistryService.find(scopeId, deviceId); if (device != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devStatus", device.getStatus().toString())); final DeviceConnection deviceConnection; if (device.getConnectionId() != null) { if (device.getConnection() != null) { deviceConnection = device.getConnection(); } else { deviceConnection = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public DeviceConnection call() throws Exception { return deviceConnectionService.find(device.getScopeId(), device.getConnectionId()); } }); } } else { deviceConnection = null; } if (deviceConnection != null) { User lastConnectedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getUserId()); } }); User reservedUser = null; if (deviceConnection.getReservedUserId() != null) { reservedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getReservedUserId()); } }); } pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", deviceConnection.getStatus().toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", lastConnectedUser != null ? lastConnectedUser.getName() : null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", reservedUser != null ? reservedUser.getName() : null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", GwtConnectionUserCouplingMode.valueOf(deviceConnection.getUserCouplingMode().name()).getLabel())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", device.getConnectionInterface())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", device.getConnectionIp())); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", deviceConnection.getStatus().toString())); } else { pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); } pairs.add(new GwtGroupedNVPair("devInfo", "devClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("devInfo", "devDisplayName", device.getDisplayName())); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new GroupDomain(), Actions.read, device.getScopeId()))) { if (device.getGroupId() != null) { Group group = groupService.find(scopeId, device.getGroupId()); if (group != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", group.getName())); } } else { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", null)); } } if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { if (device.getLastEventId() != null) { DeviceEvent lastEvent = deviceEventService.find(scopeId, device.getLastEventId()); if (lastEvent != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", lastEvent.getResource())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", lastEvent.getReceivedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } else { if (deviceConnection != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", deviceConnection.getStatus().name())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", deviceConnection.getModifiedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } } pairs.add(new GwtGroupedNVPair("devInfo", "devApps", device.getApplicationIdentifiers())); pairs.add(new GwtGroupedNVPair("devInfo", "devAccEnc", device.getAcceptEncoding())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute1", device.getCustomAttribute1())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute2", device.getCustomAttribute2())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute3", device.getCustomAttribute3())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute4", device.getCustomAttribute4())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute5", device.getCustomAttribute5())); pairs.add(new GwtGroupedNVPair("devHw", "devModelId", device.getModelId())); pairs.add(new GwtGroupedNVPair("devHw", "devModelName", device.getModelName())); pairs.add(new GwtGroupedNVPair("devHw", "devSerialNumber", device.getSerialNumber())); pairs.add(new GwtGroupedNVPair("devSw", "devFirmwareVersion", device.getFirmwareVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devBiosVersion", device.getBiosVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devOsVersion", device.getOsVersion())); pairs.add(new GwtGroupedNVPair("devJava", "devJvmVersion", device.getJvmVersion())); // GPS infos retrieval if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); DeviceEventQuery eventQuery = deviceEventFactory .newQuery(device.getScopeId()); eventQuery.setLimit(1); eventQuery.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, device.getId())); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RESOURCE, "BIRTH")); eventQuery.setPredicate(andPredicate); KapuaListResult events = deviceEventService.query(eventQuery); DeviceEvent lastEvent = events.getFirstItem(); if (lastEvent != null) { KapuaPosition eventPosition = lastEvent.getPosition(); if (eventPosition != null) { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", String.valueOf(eventPosition.getLatitude()))); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", String.valueOf(eventPosition.getLongitude()))); } } else { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", null)); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", null)); } } pairs.add(new GwtGroupedNVPair("modemInfo", "modemImei", device.getImei())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemImsi", device.getImsi())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemIccid", device.getIccid())); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return new BaseListLoadResult(pairs); } @Override public PagingLoadResult query(PagingLoadConfig loadConfig, GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); List gwtDevices = new ArrayList(); BasePagingLoadResult gwtResults; int totalResult = 0; try { DeviceQuery deviceQuery = GwtKapuaDeviceModelConverter.convertDeviceQuery(loadConfig, gwtDeviceQuery); deviceQuery.addFetchAttributes(DeviceAttributes.CONNECTION); deviceQuery.addFetchAttributes(DeviceAttributes.LAST_EVENT); KapuaListResult devices = deviceRegistryService.query(deviceQuery); totalResult = (int) deviceRegistryService.count(deviceQuery); for (Device d : devices.getItems()) { GwtDevice gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(d); // Connection info gwtDevice.setConnectionIp(d.getConnectionIp()); gwtDevice.setConnectionInterface(d.getConnectionInterface()); DeviceConnection deviceConnection = d.getConnection(); if (deviceConnection != null) { gwtDevice.setClientIp(deviceConnection.getClientIp()); gwtDevice.setGwtDeviceConnectionStatus(deviceConnection.getStatus().name()); gwtDevice.setLastEventOn(deviceConnection.getModifiedOn()); gwtDevice.setLastEventType(deviceConnection.getStatus().name()); } else { gwtDevice.setGwtDeviceConnectionStatus(GwtDeviceConnectionStatus.UNKNOWN.name()); } if (d.getLastEvent() != null) { DeviceEvent lastEvent = d.getLastEvent(); gwtDevice.setLastEventType(lastEvent.getResource()); gwtDevice.setLastEventOn(lastEvent.getReceivedOn()); } gwtDevices.add(gwtDevice); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } gwtResults = new BasePagingLoadResult(gwtDevices); gwtResults.setOffset(loadConfig != null ? loadConfig.getOffset() : 0); gwtResults.setTotalLength(totalResult); return gwtResults; } @Override public List query(GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { return query(null, gwtDeviceQuery).getData(); } @Override public GwtDevice createDevice(GwtXSRFToken xsrfToken, GwtDeviceCreator gwtDeviceCreator) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtDeviceCreator.getScopeId()); DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId, gwtDeviceCreator.getClientId()); deviceCreator.setDisplayName(gwtDeviceCreator.getDisplayName()); deviceCreator.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceCreator.getGroupId())); deviceCreator.setStatus((DeviceStatus.valueOf(gwtDeviceCreator.getDeviceStatus()))); // FIXME One day it will be specified from the form. In the meantime, defaults to LOOSE // deviceCreator.setCredentialsMode(DeviceCredentialsMode.LOOSE); deviceCreator.setCustomAttribute1(gwtDeviceCreator.getCustomAttribute1()); deviceCreator.setCustomAttribute2(gwtDeviceCreator.getCustomAttribute2()); deviceCreator.setCustomAttribute3(gwtDeviceCreator.getCustomAttribute3()); deviceCreator.setCustomAttribute4(gwtDeviceCreator.getCustomAttribute4()); deviceCreator.setCustomAttribute5(gwtDeviceCreator.getCustomAttribute5()); Device device = deviceRegistryService.create(deviceCreator); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public GwtDevice updateAttributes(GwtXSRFToken xsrfToken, GwtDevice gwtDevice) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = null; GwtDevice gwtDeviceUpdated = null; try { // // Find original device KapuaId scopeId = KapuaEid.parseCompactId(gwtDevice.getScopeId()); KapuaId deviceId = KapuaEid.parseCompactId(gwtDevice.getId()); device = deviceRegistryService.find(scopeId, deviceId); // // Updated values // Gerenal info device.setDisplayName(gwtDevice.getUnescapedDisplayName()); device.setStatus(DeviceStatus.valueOf(gwtDevice.getGwtDeviceStatus())); device.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDevice.getGroupId())); // Security Stuff // device.setCredentialsMode(DeviceCredentialsMode.valueOf(gwtDevice.getCredentialsTight())); // KapuaId deviceUserId = KapuaEid.parseCompactId(gwtDevice.getDeviceUserId()); // device.setPreferredUserId(deviceUserId); // Custom attributes device.setCustomAttribute1(gwtDevice.getUnescapedCustomAttribute1()); device.setCustomAttribute2(gwtDevice.getUnescapedCustomAttribute2()); device.setCustomAttribute3(gwtDevice.getUnescapedCustomAttribute3()); device.setCustomAttribute4(gwtDevice.getUnescapedCustomAttribute4()); device.setCustomAttribute5(gwtDevice.getUnescapedCustomAttribute5()); device.setOptlock(gwtDevice.getOptlock()); // Do the update device = deviceRegistryService.update(device); // Convert to gwt object gwtDeviceUpdated = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDeviceUpdated; } @Override public void deleteDevice(GwtXSRFToken xsrfToken, String scopeIdString, String clientId) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device d = drs.findByClientId(scopeId, clientId); drs.delete(d.getScopeId(), d.getId()); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void addDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); TagService tagService = locator.getService(TagService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); if (tagIds.contains(tagId)) { Tag tag = tagService.find(scopeId, tagId); isSameId = true; if (tag != null) { throw new KapuaDuplicateNameException(tag.getName()); } } tagIds.add(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void deleteDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); tagIds.remove(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public PagingLoadResult findDeviceEvents(PagingLoadConfig loadConfig, GwtDevice gwtDevice, Date startDate, Date endDate) throws GwtKapuaException { ArrayList gwtDeviceEvents = new ArrayList(); BasePagingLoadResult gwtResults = null; KapuaLocator locator = KapuaLocator.getInstance(); DeviceEventService des = locator.getService(DeviceEventService.class); DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); try { // prepare the query BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig; DeviceEventQuery query = deviceEventFactory.newQuery(KapuaEid.parseCompactId(gwtDevice.getScopeId())); AndPredicate andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, KapuaEid.parseCompactId(gwtDevice.getId()))); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, startDate, Operator.GREATER_THAN)); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, endDate, Operator.LESS_THAN)); query.setPredicate(andPredicate); query.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); query.setOffset(bplc.getOffset()); query.setLimit(bplc.getLimit()); // query execute KapuaListResult deviceEvents = des.query(query); // prepare results for (DeviceEvent deviceEvent : deviceEvents.getItems()) { gwtDeviceEvents.add(KapuaGwtDeviceModelConverter.convertDeviceEvent(deviceEvent)); } gwtResults = new BasePagingLoadResult(gwtDeviceEvents); gwtResults.setOffset(loadConfig.getOffset()); gwtResults.setTotalLength((int) des.count(query)); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtResults; } @Override public String getTileEndpoint() throws GwtKapuaException { return ConsoleSetting.getInstance().getString(ConsoleSettingKeys.DEVICE_MAP_TILE_URI); } @Override public boolean isMapEnabled() { return ConsoleSetting.getInstance().getBoolean(ConsoleSettingKeys.DEVICE_MAP_ENABLED); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 5915 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java/#L88-L581 | 2 | 593 | 5915 | major |
| 1329 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | long method | t | t | f | long method | data class | 0 | 10707 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 1329 | 10707 | critical |
| 2249 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | long method | t | t | f | long method | data class | 0 | 13663 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 2249 | 13663 | minor |
| 1708 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GlobbingPathHelper { /** * Converts the provided path containing glob characters * * and ** into a regular expression. The definition matches * that of the GlobbingPathFilter with the addition that this conversion * also supports sub-paths which do not start with a /. * * The rules are: * * leading ** matches /foo and bar * leading /** matches /foo but not bar * intermittent ** matches zero or any number of path elements * trailing ** matches anything not ending with a / * single * matches anything except / * ? is not a special character * anything not a star is wrapped into \Q...\E pairs * * @param pathWithGlobs path that can contain * and ** * @return a regular expression * @see GlobbingPathFilter */ public static String globPathAsRegex(String pathWithGlobs) { if (pathWithGlobs == null) { return null; } else if (!pathWithGlobs.contains("*")) { return pathWithGlobs; } List elements = Lists.newLinkedList(elements(pathWithGlobs)); StringBuffer sb = new StringBuffer(); sb.append("\\Q"); if (pathWithGlobs.startsWith("/")) { sb.append("/"); } if (elements.get(0).equals("**")) { sb.append("\\E[^/]*(/[^/]*)*\\Q"); elements.remove(0); } int size = elements.size(); boolean endsWithStarStar = size == 0 ? false : elements.get(size - 1).equals("**"); if (endsWithStarStar) { elements.remove(size - 1); } boolean addSlash = false; for(int i=0; i<elements.size(); i++) { String pathElem = elements.get(i); if (addSlash) { sb.append("/"); } if (pathElem.equals("**")) { addSlash = false; sb.append("\\E([^/]*/)*\\Q"); } else { sb.append(pathElem.replace("*", "\\E[^/]*\\Q")); addSlash = true; } } if (endsWithStarStar) { sb.append("\\E(/[^/]*)*"); } else if (pathWithGlobs.endsWith("/")) { sb.append("/\\E"); } else { sb.append("\\E"); } return sb.toString(); } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 11756 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/observation/filter/GlobbingPathHelper.java/#L27-L94 | 1 | 1708 | 11756 | minor |
| 370 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Class getPropertyEditorClass(final Object bean, final String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 3845 | https://github.com/apache/commons-beanutils/blob/33a067788f2a414c0b019f8d8974cc455c1982a4/src/main/java/org/apache/commons/beanutils2/PropertyUtils.java/#L458-L464 | 1 | 370 | 3845 | critical |
| 836 | " YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditionals 5. High coupling 6. Inappropriate naming 7. Unnecessary comments 8. Data clumps 9. Magic numbers 10. Data class 11. Lazy class 12. Long parameter list 13. Message chains 14. Shotgun surgery 15. Large class 16. Temporary fields 17. Switch statements 18. Redundant code 19. Dead code 20. Shotgun surgery 21. Empty catch clauses | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | Long method 2 Feature envy 3 Duplicate code 4 Complex conditionals 5 High coupling 6 Inappropriate naming 7 Unnecessary comments 8 Data clumps 9 Magic numbers | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Complex conditionals 5. High coupling 6. Inappropriate naming 7. Unnecessary comments 8. Data clumps 9. Magic numbers | blob | 0 | 7756 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 2 | 836 | 7756 | major |
| 3794 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Not specified | f | f | f | false | 0 | 9585 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 1 | 3794 | 9585 | minor | |
| 741 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 6975 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 741 | 6975 | minor |
| 1979 | { "output": "YES I found bad smells", "the bad smells are:": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12634 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 2 | 1979 | 12634 | critical |
| 2659 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorTestCaseFinder { private static final Logger log = LoggerFactory.getLogger(IteratorTestCaseFinder.class); /** * Instantiates all test cases provided. * * @return A list of {@link IteratorTestCase}s. */ public static List findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet classes = cp .getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List testCases = new ArrayList<>(); // final Set> classes = // reflections.getSubTypesOf(IteratorTestCase.class); for (ClassInfo classInfo : classes) { Class clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 15189 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/iterator-test-harness/src/main/java/org/apache/accumulo/iteratortest/IteratorTestCaseFinder.java/#L35-L81 | 2 | 2659 | 15189 | minor |
| 2225 | YES I found bad smells the bad smells are: 1. Meaningless comments, 2. DirectOwnership | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | Meaningless comments, 2 DirectOwnership | t | f | f | . Meaningless comments, 2. DirectOwnership | data class | 0 | 13573 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 2225 | 13573 | major |
| 1919 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12412 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1919 | 12412 | major |
| 325 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WebServer { public static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private HttpServer2 httpServer; private final HasConfig conf; private InetSocketAddress httpAddress; private InetSocketAddress httpsAddress; protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver"; public WebServer(HasConfig conf) { this.conf = conf; } public HasConfig getConf() { return conf; } private void init() { final String pathSpec = "/has/v1/*"; // add has packages httpServer.addJerseyResourcePackage(AsRequestApi.class .getPackage().getName(), pathSpec); } public void defineFilter() { String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType.equals("kerberos")) { // add authentication filter for webhdfs final String className = conf.getString( WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY, WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT); final String name = className; Map params = getAuthFilterParams(conf); String kadminPathSpec = "/has/v1/kadmin/*"; String hadminPathSpec = "/has/v1/hadmin/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className, params, new String[]{kadminPathSpec, hadminPathSpec}); HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className + ")"); } } public void defineConfFilter() { String confFilterName = ConfFilter.class.getName(); String confPath = "/has/v1/conf/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName, getAuthFilterParams(conf), new String[]{confPath}); HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName + ")"); } private Map getAuthFilterParams(HasConfig conf) { Map params = new HashMap<>(); String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType != null && !authType.isEmpty()) { params.put(AuthenticationFilter.AUTH_TYPE, authType); } String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY); if (principal != null && !principal.isEmpty()) { try { principal = SecurityUtil.getServerPrincipal(principal, getHttpsAddress().getHostName()); } catch (IOException e) { LOG.warn("Errors occurred when get server principal. " + e.getMessage()); } params.put(KerberosAuthenticationHandler.PRINCIPAL, principal); } String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY); if (keytab != null && !keytab.isEmpty()) { params.put(KerberosAuthenticationHandler.KEYTAB, keytab); } String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES); if (rule != null && !rule.isEmpty()) { params.put(KerberosAuthenticationHandler.NAME_RULES, rule); } else { params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT"); } return params; } public InetSocketAddress getBindAddress() { if (httpAddress != null) { return httpAddress; } else if (httpsAddress != null) { return httpsAddress; } else { return null; } } /** * for information related to the different configuration options and * Http Policy is decided. * * @throws HasException HAS exception when starting web server */ public void start() throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); final String bindHost = conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY); InetSocketAddress httpAddr = null; if (policy.isHttpEnabled()) { final String httpAddrString = conf.getString( WebConfigKey.HAS_HTTP_ADDRESS_KEY, WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT); httpAddr = NetUtils.createSocketAddr(httpAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort()); } LOG.info("Get the http address: " + httpAddr); } InetSocketAddress httpsAddr = null; if (policy.isHttpsEnabled()) { final String httpsAddrString = conf.getString( WebConfigKey.HAS_HTTPS_ADDRESS_KEY, WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT); httpsAddr = NetUtils.createSocketAddr(httpsAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort()); } LOG.info("Get the https address: " + httpsAddr); } HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has"); try { httpServer = builder.build(); } catch (IOException e) { throw new HasException("Errors occurred when building http server. " + e.getMessage()); } init(); try { httpServer.start(); } catch (IOException e) { throw new HasException("Errors occurred when starting http server. " + e.getMessage()); } int connIdx = 0; if (policy.isHttpEnabled()) { httpAddress = httpServer.getConnectorAddress(connIdx++); if (httpAddress != null) { conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, NetUtils.getHostPortString(httpAddress)); } } if (policy.isHttpsEnabled()) { httpsAddress = httpServer.getConnectorAddress(connIdx); if (httpsAddress != null) { conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, NetUtils.getHostPortString(httpsAddress)); } } } public void setWebServerAttribute(HasServer hasServer) { httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer); } public static HasServer getHasServerFromContext(ServletContext context) { return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY); } /** * Get http policy. * * @param conf the HAS config * @return HttpConfig.Policy the policy */ public HttpConfig.Policy getHttpPolicy(HasConfig conf) { String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY, WebConfigKey.HAS_HTTP_POLICY_DEFAULT); HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr); if (policy == null) { throw new HadoopIllegalArgumentException("Unrecognized value '" + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY); } conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name()); return policy; } /** * Return a HttpServer.Builder that the HAS can use to * initialize their HTTP / HTTPS server. * * @param conf the HAS config * @param httpAddr the InetSocketAddress of http * @param httpsAddr the InetSocketAddress of https * @param name the host name * @return HttpServer2.Builder the builder * @throws HasException HAS exception */ public HttpServer2.Builder httpServerTemplateForHAS( HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name) throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); HttpServer2.Builder builder = new HttpServer2.Builder().setName(name); if (policy.isHttpEnabled()) { if (httpAddr != null && httpAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } if (policy.isHttpsEnabled() && httpsAddr != null) { HasConfig sslConf = loadSslConfiguration(conf); loadSslConfToHttpServerBuilder(builder, sslConf); if (httpsAddr != null && httpsAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } return builder; } /** * Load HTTPS-related configuration. * * @param conf HAS config * @return HasConfig after loading ssl configuration * @throws HasException HAS exception when loading HTTPS related configuration */ public HasConfig loadSslConfiguration(HasConfig conf) throws HasException { HasConfig sslConf = new HasConfig(); String sslConfigString = conf.getString( WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT); LOG.info("Get the ssl config file: " + sslConfigString); File sslConfig = new File(sslConfigString); if (!sslConfig.exists()) { throw new HasException("The ssl server config file " + sslConfigString + " does not exist."); } try { sslConf.addIniConfig(sslConfig); } catch (IOException e) { throw new HasException("Errors occurred when adding config. " + e.getMessage()); } final String[] reqSslProps = { WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY }; // Check if the required properties are included for (String sslProp : reqSslProps) { if (sslConf.getString(sslProp) == null) { LOG.warn("SSL config " + sslProp + " is missing. If " + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY + " is specified, make sure it is a relative path"); } } boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT); sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth); return sslConf; } public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder, HasConfig sslConf) { return builder .needsClientAuth( sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT)) .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY)) .keyStore(sslConf.getString("ssl.server.keystore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.keystore.type", "jks")) .trustStore(sslConf.getString("ssl.server.truststore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.truststore.type", "jks")) .excludeCiphers( sslConf.getString("ssl.server.exclude.cipher.list")); } /** * Leverages the Configuration.getPassword method to attempt to get * passwords from the CredentialProvider API before falling back to * clear text in config - if falling back is allowed. * * @param conf Configuration instance * @param alias name of the credential to retreive * @return String credential value or null */ public String getPassword(HasConfig conf, String alias) { return conf.getString(alias); } public void stop() throws Exception { if (httpServer != null) { httpServer.stop(); } } public InetSocketAddress getHttpAddress() { return httpAddress; } public InetSocketAddress getHttpsAddress() { return httpsAddress; } } |
blob | f | f | f | blob | 0 | 3358 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java/#L43-L374 | 1 | 325 | 3358 | major | ||
| 1705 | {"answer": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } } |
blob | data class | t | t | f | data class | blob | 0 | 11749 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 | 1 | 1705 | 11749 | major |
| 1973 | YES I found bad smells the bad smells are: None | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | None | t | f | f | None | long method | 0 | 12612 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 2 | 1973 | 12612 | minor |
| 2406 | {"response": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | blob | t | t | f | blob | data class | 0 | 14388 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 1 | 2406 | 14388 | minor |
| 863 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExecutorTransfer { private static final Logger LOG = LoggerFactory.getLogger(ExecutorTransfer.class); private final WorkerState workerData; private final KryoTupleSerializer serializer; private final boolean isDebug; private int indexingBase = 0; private ArrayList localReceiveQueues; // [taskId-indexingBase] => queue : List of all recvQs local to this worker private AtomicReferenceArray queuesToFlush; // [taskId-indexingBase] => queue, some entries can be null. : outbound Qs for this executor instance public ExecutorTransfer(WorkerState workerData, Map topoConf) { this.workerData = workerData; this.serializer = new KryoTupleSerializer(topoConf, workerData.getWorkerTopologyContext()); this.isDebug = ObjectReader.getBoolean(topoConf.get(Config.TOPOLOGY_DEBUG), false); } // to be called after all Executor objects in the worker are created and before this object is used public void initLocalRecvQueues() { Integer minTaskId = workerData.getLocalReceiveQueues().keySet().stream().min(Integer::compareTo).get(); this.localReceiveQueues = Utils.convertToArray(workerData.getLocalReceiveQueues(), minTaskId); this.indexingBase = minTaskId; this.queuesToFlush = new AtomicReferenceArray(localReceiveQueues.size()); } // adds addressedTuple to destination Q if it is not full. else adds to pendingEmits (if its not null) public boolean tryTransfer(AddressedTuple addressedTuple, Queue pendingEmits) { if (isDebug) { LOG.info("TRANSFERRING tuple {}", addressedTuple); } JCQueue localQueue = getLocalQueue(addressedTuple); if (localQueue != null) { return tryTransferLocal(addressedTuple, localQueue, pendingEmits); } return workerData.tryTransferRemote(addressedTuple, pendingEmits, serializer); } // flushes local and remote messages public void flush() throws InterruptedException { flushLocal(); workerData.flushRemotes(); } private void flushLocal() throws InterruptedException { for (int i = 0; i < queuesToFlush.length(); i++) { JCQueue q = queuesToFlush.get(i); if (q != null) { q.flush(); queuesToFlush.set(i, null); } } } public JCQueue getLocalQueue(AddressedTuple tuple) { if ((tuple.dest - indexingBase) >= localReceiveQueues.size()) { return null; } return localReceiveQueues.get(tuple.dest - indexingBase); } /** * Adds tuple to localQueue (if overflow is empty). If localQueue is full adds to pendingEmits instead. pendingEmits can be null. * Returns false if unable to add to localQueue. */ public boolean tryTransferLocal(AddressedTuple tuple, JCQueue localQueue, Queue pendingEmits) { workerData.checkSerialize(serializer, tuple); if (pendingEmits != null) { if (pendingEmits.isEmpty() && localQueue.tryPublish(tuple)) { queuesToFlush.set(tuple.dest - indexingBase, localQueue); return true; } else { pendingEmits.add(tuple); return false; } } else { return localQueue.tryPublish(tuple); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7912 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/executor/ExecutorTransfer.java/#L30-L113 | 1 | 863 | 7912 | minor |
| 1780 | {"response": "YES I found bad smells", "the bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GwtDeviceServiceImpl extends KapuaRemoteServiceServlet implements GwtDeviceService { private static final long serialVersionUID = -1391026997499175151L; private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private boolean isSameId; @Override public GwtDevice findDevice(String scopeIdString, String deviceIdString) throws GwtKapuaException { GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = deviceRegistryService.find(scopeId, deviceId); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public ListLoadResult findDeviceProfile(String scopeIdString, String deviceIdString) throws GwtKapuaException { List pairs = new ArrayList(); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceEventService deviceEventService = locator.getService(DeviceEventService.class); final DeviceConnectionService deviceConnectionService = locator.getService(DeviceConnectionService.class); GroupService groupService = locator.getService(GroupService.class); final UserService userService = locator.getService(UserService.class); try { final KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); final Device device = deviceRegistryService.find(scopeId, deviceId); if (device != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devStatus", device.getStatus().toString())); final DeviceConnection deviceConnection; if (device.getConnectionId() != null) { if (device.getConnection() != null) { deviceConnection = device.getConnection(); } else { deviceConnection = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public DeviceConnection call() throws Exception { return deviceConnectionService.find(device.getScopeId(), device.getConnectionId()); } }); } } else { deviceConnection = null; } if (deviceConnection != null) { User lastConnectedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getUserId()); } }); User reservedUser = null; if (deviceConnection.getReservedUserId() != null) { reservedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getReservedUserId()); } }); } pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", deviceConnection.getStatus().toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", lastConnectedUser != null ? lastConnectedUser.getName() : null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", reservedUser != null ? reservedUser.getName() : null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", GwtConnectionUserCouplingMode.valueOf(deviceConnection.getUserCouplingMode().name()).getLabel())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", device.getConnectionInterface())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", device.getConnectionIp())); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", deviceConnection.getStatus().toString())); } else { pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); } pairs.add(new GwtGroupedNVPair("devInfo", "devClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("devInfo", "devDisplayName", device.getDisplayName())); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new GroupDomain(), Actions.read, device.getScopeId()))) { if (device.getGroupId() != null) { Group group = groupService.find(scopeId, device.getGroupId()); if (group != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", group.getName())); } } else { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", null)); } } if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { if (device.getLastEventId() != null) { DeviceEvent lastEvent = deviceEventService.find(scopeId, device.getLastEventId()); if (lastEvent != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", lastEvent.getResource())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", lastEvent.getReceivedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } else { if (deviceConnection != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", deviceConnection.getStatus().name())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", deviceConnection.getModifiedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } } pairs.add(new GwtGroupedNVPair("devInfo", "devApps", device.getApplicationIdentifiers())); pairs.add(new GwtGroupedNVPair("devInfo", "devAccEnc", device.getAcceptEncoding())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute1", device.getCustomAttribute1())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute2", device.getCustomAttribute2())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute3", device.getCustomAttribute3())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute4", device.getCustomAttribute4())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute5", device.getCustomAttribute5())); pairs.add(new GwtGroupedNVPair("devHw", "devModelId", device.getModelId())); pairs.add(new GwtGroupedNVPair("devHw", "devModelName", device.getModelName())); pairs.add(new GwtGroupedNVPair("devHw", "devSerialNumber", device.getSerialNumber())); pairs.add(new GwtGroupedNVPair("devSw", "devFirmwareVersion", device.getFirmwareVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devBiosVersion", device.getBiosVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devOsVersion", device.getOsVersion())); pairs.add(new GwtGroupedNVPair("devJava", "devJvmVersion", device.getJvmVersion())); // GPS infos retrieval if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); DeviceEventQuery eventQuery = deviceEventFactory .newQuery(device.getScopeId()); eventQuery.setLimit(1); eventQuery.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, device.getId())); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RESOURCE, "BIRTH")); eventQuery.setPredicate(andPredicate); KapuaListResult events = deviceEventService.query(eventQuery); DeviceEvent lastEvent = events.getFirstItem(); if (lastEvent != null) { KapuaPosition eventPosition = lastEvent.getPosition(); if (eventPosition != null) { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", String.valueOf(eventPosition.getLatitude()))); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", String.valueOf(eventPosition.getLongitude()))); } } else { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", null)); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", null)); } } pairs.add(new GwtGroupedNVPair("modemInfo", "modemImei", device.getImei())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemImsi", device.getImsi())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemIccid", device.getIccid())); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return new BaseListLoadResult(pairs); } @Override public PagingLoadResult query(PagingLoadConfig loadConfig, GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); List gwtDevices = new ArrayList(); BasePagingLoadResult gwtResults; int totalResult = 0; try { DeviceQuery deviceQuery = GwtKapuaDeviceModelConverter.convertDeviceQuery(loadConfig, gwtDeviceQuery); deviceQuery.addFetchAttributes(DeviceAttributes.CONNECTION); deviceQuery.addFetchAttributes(DeviceAttributes.LAST_EVENT); KapuaListResult devices = deviceRegistryService.query(deviceQuery); totalResult = (int) deviceRegistryService.count(deviceQuery); for (Device d : devices.getItems()) { GwtDevice gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(d); // Connection info gwtDevice.setConnectionIp(d.getConnectionIp()); gwtDevice.setConnectionInterface(d.getConnectionInterface()); DeviceConnection deviceConnection = d.getConnection(); if (deviceConnection != null) { gwtDevice.setClientIp(deviceConnection.getClientIp()); gwtDevice.setGwtDeviceConnectionStatus(deviceConnection.getStatus().name()); gwtDevice.setLastEventOn(deviceConnection.getModifiedOn()); gwtDevice.setLastEventType(deviceConnection.getStatus().name()); } else { gwtDevice.setGwtDeviceConnectionStatus(GwtDeviceConnectionStatus.UNKNOWN.name()); } if (d.getLastEvent() != null) { DeviceEvent lastEvent = d.getLastEvent(); gwtDevice.setLastEventType(lastEvent.getResource()); gwtDevice.setLastEventOn(lastEvent.getReceivedOn()); } gwtDevices.add(gwtDevice); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } gwtResults = new BasePagingLoadResult(gwtDevices); gwtResults.setOffset(loadConfig != null ? loadConfig.getOffset() : 0); gwtResults.setTotalLength(totalResult); return gwtResults; } @Override public List query(GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { return query(null, gwtDeviceQuery).getData(); } @Override public GwtDevice createDevice(GwtXSRFToken xsrfToken, GwtDeviceCreator gwtDeviceCreator) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtDeviceCreator.getScopeId()); DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId, gwtDeviceCreator.getClientId()); deviceCreator.setDisplayName(gwtDeviceCreator.getDisplayName()); deviceCreator.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceCreator.getGroupId())); deviceCreator.setStatus((DeviceStatus.valueOf(gwtDeviceCreator.getDeviceStatus()))); // FIXME One day it will be specified from the form. In the meantime, defaults to LOOSE // deviceCreator.setCredentialsMode(DeviceCredentialsMode.LOOSE); deviceCreator.setCustomAttribute1(gwtDeviceCreator.getCustomAttribute1()); deviceCreator.setCustomAttribute2(gwtDeviceCreator.getCustomAttribute2()); deviceCreator.setCustomAttribute3(gwtDeviceCreator.getCustomAttribute3()); deviceCreator.setCustomAttribute4(gwtDeviceCreator.getCustomAttribute4()); deviceCreator.setCustomAttribute5(gwtDeviceCreator.getCustomAttribute5()); Device device = deviceRegistryService.create(deviceCreator); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public GwtDevice updateAttributes(GwtXSRFToken xsrfToken, GwtDevice gwtDevice) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = null; GwtDevice gwtDeviceUpdated = null; try { // // Find original device KapuaId scopeId = KapuaEid.parseCompactId(gwtDevice.getScopeId()); KapuaId deviceId = KapuaEid.parseCompactId(gwtDevice.getId()); device = deviceRegistryService.find(scopeId, deviceId); // // Updated values // Gerenal info device.setDisplayName(gwtDevice.getUnescapedDisplayName()); device.setStatus(DeviceStatus.valueOf(gwtDevice.getGwtDeviceStatus())); device.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDevice.getGroupId())); // Security Stuff // device.setCredentialsMode(DeviceCredentialsMode.valueOf(gwtDevice.getCredentialsTight())); // KapuaId deviceUserId = KapuaEid.parseCompactId(gwtDevice.getDeviceUserId()); // device.setPreferredUserId(deviceUserId); // Custom attributes device.setCustomAttribute1(gwtDevice.getUnescapedCustomAttribute1()); device.setCustomAttribute2(gwtDevice.getUnescapedCustomAttribute2()); device.setCustomAttribute3(gwtDevice.getUnescapedCustomAttribute3()); device.setCustomAttribute4(gwtDevice.getUnescapedCustomAttribute4()); device.setCustomAttribute5(gwtDevice.getUnescapedCustomAttribute5()); device.setOptlock(gwtDevice.getOptlock()); // Do the update device = deviceRegistryService.update(device); // Convert to gwt object gwtDeviceUpdated = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDeviceUpdated; } @Override public void deleteDevice(GwtXSRFToken xsrfToken, String scopeIdString, String clientId) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device d = drs.findByClientId(scopeId, clientId); drs.delete(d.getScopeId(), d.getId()); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void addDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); TagService tagService = locator.getService(TagService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); if (tagIds.contains(tagId)) { Tag tag = tagService.find(scopeId, tagId); isSameId = true; if (tag != null) { throw new KapuaDuplicateNameException(tag.getName()); } } tagIds.add(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void deleteDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); tagIds.remove(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public PagingLoadResult findDeviceEvents(PagingLoadConfig loadConfig, GwtDevice gwtDevice, Date startDate, Date endDate) throws GwtKapuaException { ArrayList gwtDeviceEvents = new ArrayList(); BasePagingLoadResult gwtResults = null; KapuaLocator locator = KapuaLocator.getInstance(); DeviceEventService des = locator.getService(DeviceEventService.class); DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); try { // prepare the query BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig; DeviceEventQuery query = deviceEventFactory.newQuery(KapuaEid.parseCompactId(gwtDevice.getScopeId())); AndPredicate andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, KapuaEid.parseCompactId(gwtDevice.getId()))); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, startDate, Operator.GREATER_THAN)); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, endDate, Operator.LESS_THAN)); query.setPredicate(andPredicate); query.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); query.setOffset(bplc.getOffset()); query.setLimit(bplc.getLimit()); // query execute KapuaListResult deviceEvents = des.query(query); // prepare results for (DeviceEvent deviceEvent : deviceEvents.getItems()) { gwtDeviceEvents.add(KapuaGwtDeviceModelConverter.convertDeviceEvent(deviceEvent)); } gwtResults = new BasePagingLoadResult(gwtDeviceEvents); gwtResults.setOffset(loadConfig.getOffset()); gwtResults.setTotalLength((int) des.count(query)); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtResults; } @Override public String getTileEndpoint() throws GwtKapuaException { return ConsoleSetting.getInstance().getString(ConsoleSettingKeys.DEVICE_MAP_TILE_URI); } @Override public boolean isMapEnabled() { return ConsoleSetting.getInstance().getBoolean(ConsoleSettingKeys.DEVICE_MAP_ENABLED); } } |
blob | long method | t | t | f | long method | blob | 0 | 11961 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java/#L88-L581 | 1 | 1780 | 11961 | critical |
| 2442 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14482 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 2442 | 14482 | minor |
| 2396 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14374 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2396 | 14374 | minor |
| 1798 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component("org.apache.usergrid.rest.management.organizations.applications.ApplicationResource") @Scope("prototype") @Produces({ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", "text/jscript" }) public class ApplicationResource extends AbstractContextResource { private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); public static final String CONFIRM_APPLICATION_IDENTIFIER = "confirm_application_identifier"; public static final String RESTORE_PASSWORD = "restore_password"; //@Autowired //protected ExportService exportService; OrganizationInfo organization; UUID applicationId; ApplicationInfo application; @Autowired private SignInProviderFactory signInProviderFactory; public ApplicationResource() { } public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { this.organization = organization; this.applicationId = applicationId; return this; } public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { this.organization = organization; applicationId = application.getId(); this.application = application; return this; } @RequireOrganizationAccess @GET @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getApplication( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); ServiceManager sm = smf.getServiceManager( applicationId ); response.setAction( "get" ); response.setApplication( sm.getApplication() ); response.setParams( ui.getQueryParameters() ); response.setResults( management.getApplicationMetadata( applicationId ) ); return response; } @RequireOrganizationAccess @GET @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get application client credentials"); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.getClientSecretForApplication( applicationId ) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @POST @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse generateCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "generate application client credentials" ); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.newClientSecretForApplication(applicationId) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @GET @JSONP @Path("_size") public ApiResponse getApplicationSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "get application size for all entities" ); long size = management.getApplicationSize(this.applicationId); Map map = new HashMap<>(); Map innerMap = new HashMap<>(); Map sumMap = new HashMap<>(); innerMap.put("application",size); sumMap.put("size",innerMap); map.put("aggregation", sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("{collection_name}/_size") public ApiResponse getCollectionSize( @Context UriInfo ui, @PathParam( "collection_name" ) String collection_name, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); long size = management.getCollectionSize(this.applicationId, collection_name); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); Map innerMap = new HashMap<>(); innerMap.put(collection_name,size); sumMap.put("size",innerMap); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("collections/_size") public ApiResponse getEachCollectionSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); Map sizes = management.getEachCollectionSize(this.applicationId); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); sumMap.put("size",sizes); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @POST @Path("sia-provider") @Consumes(APPLICATION_JSON) @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, Map json, @QueryParam("callback") @DefaultValue("") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "post signin provider configuration" ); Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); SignInAsProvider signInAsProvider = null; if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { signInAsProvider = signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { signInAsProvider = signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { signInAsProvider = signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); } Preconditions.checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); signInAsProvider.saveToConfiguration( json ); return response; } // @POST // @Path("export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // // UUID jobUUID = null; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( bucketName == null ) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // json.put("organizationId", organization.getUuid()); // json.put( "applicationId",applicationId); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // catch ( Exception e ) { // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // return Response.status( SC_INTERNAL_SERVER_ERROR ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // @POST // @Path("collection/{collection_name}/export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui, // @PathParam( "collection_name" ) String collection_name ,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // UUID jobUUID = null; // String colExport = collection_name; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // //checkJsonExportProperties(json); // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // if(bucketName == null) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // // json.put( "organizationId",organization.getUuid() ); // json.put( "applicationId", applicationId); // json.put( "collectionName", colExport); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ) // .build(); // } // catch ( Exception e ) { // // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // // OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_INTERNAL_SERVER_ERROR ) // .setErrorDescription( e.getMessage() ) // .buildJSONMessage(); // // return Response.status( errorMsg.getResponseStatus() ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ) // .build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // // @Path( "imports" ) // public ImportsResource importGetJson( @Context UriInfo ui, // @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) // throws Exception { // // // return getSubResource( ImportsResource.class ).init( organization, application ); // } @GET @Path("/status") public Response getStatus() { Map statusMap = new HashMap(); EntityManager em = emf.getEntityManager( applicationId ); if ( !emf.getIndexHealth().equals( Health.RED ) ) { statusMap.put("message", "Index Health Status RED for application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } try { if ( em.getApplication() == null ) { statusMap.put("message", "Application " + applicationId + " not found"); return Response.status( SC_NOT_FOUND ).entity( statusMap ).build(); } } catch (Exception ex) { statusMap.put("message", "Error looking up application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } return Response.status( SC_OK ).entity( null ).build(); } /** * Put on application URL will restore application if it was deleted. */ @PUT @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executePut( @Context UriInfo ui, String body, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if ( applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (!SubjectUtils.isServiceAdmin()) { // require password if it exists String storedRestorePassword = restorePasswordService.getApplicationRestorePassword(applicationId); if (StringUtils.isNotEmpty(storedRestorePassword)) { // must have matching password as query parameter String suppliedRestorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (!storedRestorePassword.equals(suppliedRestorePassword)) { throw new IllegalArgumentException("Application cannot be restored without application password"); } } } management.restoreApplication( applicationId ); // not deleting password -- will be changed upon successful soft delete ApiResponse response = createApiResponse(); response.setAction( "restore" ); response.setApplication( emf.getEntityManager( applicationId ).getApplication() ); response.setParams( ui.getQueryParameters() ); return response; } /** * Caller MUST pass confirm_application_identifier that is either the UUID or the * name of the application to be deleted. Yes, this is redundant and intended to * be a protection measure to force caller to confirm that they want to do a delete. */ @DELETE @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executeDelete( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback, @QueryParam(CONFIRM_APPLICATION_IDENTIFIER) String confirmApplicationIdentifier) throws Exception { if ( application == null && applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } // If the path uses name then expect name, otherwise if they use uuid then expect uuid. if (application == null) { if (!applicationId.toString().equals( confirmApplicationIdentifier )) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application id."); } } else if (!application.getName().split( "/" )[1].equals( confirmApplicationIdentifier ) ) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application name"); } String restorePassword = null; ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (SubjectUtils.isServiceAdmin()) { restorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (StringUtils.isNotEmpty(restorePassword)) { // save password, required for future undelete if not sysadmin restorePasswordService.setApplicationRestorePassword(applicationId, restorePassword); } } management.deleteApplication( applicationId ); if (restorePassword == null) { // clear restore password restorePasswordService.removeApplicationRestorePassword(applicationId); } if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() deleted appId = {}", applicationId); } ApiResponse response = createApiResponse(); response.setAction( "delete" ); response.setApplication(emf.getEntityManager( applicationId ).getApplication()); response.setParams(ui.getQueryParameters()); if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() sending response "); } return response; } private ApplicationRestorePasswordService getApplicationRestorePasswordService() { return injector.getInstance(ApplicationRestorePasswordService.class); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 12006 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/rest/src/main/java/org/apache/usergrid/rest/management/organizations/applications/ApplicationResource.java/#L63-L563 | 2 | 1798 | 12006 | major |
| 285 | YES, I found bad smells the bad smells are: 1. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void securityConfEdited() { // Need to call explicitly since we will not get notified of changes to local security.json cores.securityNodeChanged(); } |
feature envy | Magic numbers | t | f | f | . Magic numbers | feature envy | 0 | 3055 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/admin/SecurityConfHandlerLocal.java/#L99-L103 | 2 | 285 | 3055 | minor |
| 1791 | {"message": "YES I found bad smells", "details": {"bad_smells": ["Blob"]}} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | 'bad_smells': 'Blob' | t | t | f | {',b,a,d,_,s,m,e,l,l,s,',:," ",',B,l,o,b,'} | {',b,d,_,m,',:," ",',B,o,b,'} | 0 | 11988 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 1791 | 11988 | minor |
| 2204 | YES, I found bad smells the bad smells are: 1. Long method 2. Repeated code 3. Constructor overloading with similar functionality 4. Lack of comments/documentation 5. Primitive obsession (using primitive types instead of creating a separate object) 6. Low cohesion (no common purpose or functionality in the class) 7. Poor naming conventions (unclear or generic names for variables and methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method2 Repeated code3 Constructor overloading with similar functionality4 Lack of comments/documentation5 Primitive obsession (using primitive types instead of creating a separate object)6 Low cohesion (no common purpose or functionality in the class)7 Poor naming conventions (unclear or generic names for variables and methods) | t | f | f | . Long method2. Repeated code3. Constructor overloading with similar functionality4. Lack of comments/documentation5. Primitive obsession (using primitive types instead of creating a separate object)6. Low cohesion (no common purpose or functionality in the class)7. Poor naming conventions (unclear or generic names for variables and methods) | data class | 0 | 13510 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 2204 | 13510 | minor |
| 1232 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10367 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1232 | 10367 | major |
| 485 | YES, I found bad smells 1. Long method 2. Feature envy 3. Code duplication (repeated code blocks in newInstance() and getAnnotationTypeArray()) 4. Dead code (getJavaClassName(), getClassLoader(), getSuperClassStructure() and getAccess() methods are not used) 5. Null check in newInstance() and newInstances() methods are not necessary as parameter cannot be null. 6. Magic number (0 in annotationTypeClassStructuresLazyGet.get() method) 7. Lazy initialization of collections (annotationTypeClassStructuresLazyGet and behaviorStructuresLazyGet) 8. Complex method newBehaviorStructure() - violates Single Responsibility Principle 9. Use of LazyGet class seems unnecessary and adds unnecessary complexity to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } } |
blob | Long method2 Feature envy3 Code duplication (repeated code blocks in newInstance() and getAnnotationTypeArray())4 Dead code (getJavaClassName(), getClassLoader(), getSuperClassStructure() and getAccess() methods are not used)5 Null check in newInstance() and newInstances() methods are not necessary as parameter cannot be null6 Magic number (0 in annotationTypeClassStructuresLazyGetget() method)7 Lazy initialization of collections (annotationTypeClassStructuresLazyGet and behaviorStructuresLazyGet)8 Complex method newBehaviorStructure() - violates Single Responsibility Principle9 Use of LazyGet class seems unnecessary and adds unnecessary complexity to the code | t | f | f | . Long method2. Feature envy3. Code duplication (repeated code blocks in newInstance() and getAnnotationTypeArray())4. Dead code (getJavaClassName(), getClassLoader(), getSuperClassStructure() and getAccess() methods are not used)5. Null check in newInstance() and newInstances() methods are not necessary as parameter cannot be null.6. Magic number (0 in annotationTypeClassStructuresLazyGet.get() method)7. Lazy initialization of collections (annotationTypeClassStructuresLazyGet and behaviorStructuresLazyGet)8. Complex method newBehaviorStructure() - violates Single Responsibility Principle9. Use of LazyGet class seems unnecessary and adds unnecessary complexity to the code. | blob | 0 | 4746 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 | 2 | 485 | 4746 | minor |
| 382 | YES I found bad smells the bad smells are: 1.Long method, 2. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long method, 2 Shotgun surgery | t | f | f | .Long method, 2. Shotgun surgery | data class | 0 | 3913 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 382 | 3913 | major |
| 2319 | SequenceFileReader YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SequenceFileReader extends AbstractFileReader { public static final String[] defaultFields = { "key", "value" }; public static final String BUFFER_SIZE = "hdfsspout.reader.buffer.bytes"; private static final Logger LOG = LoggerFactory .getLogger(SequenceFileReader.class); private static final int DEFAULT_BUFF_SIZE = 4096; private final SequenceFile.Reader reader; private final SequenceFileReader.Offset offset; private final Key key; private final Value value; public SequenceFileReader(FileSystem fs, Path file, Map conf) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); this.offset = new SequenceFileReader.Offset(0, 0, 0); } public SequenceFileReader(FileSystem fs, Path file, Map conf, String offset) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.offset = new SequenceFileReader.Offset(offset); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); skipToOffset(this.reader, this.offset, this.key); } private static void skipToOffset(SequenceFile.Reader reader, Offset offset, K key) throws IOException { reader.sync(offset.lastSyncPoint); for (int i = 0; i < offset.recordsSinceLastSync; ++i) { reader.next(key); } } public List next() throws IOException, ParseException { if (reader.next(key, value)) { ArrayList result = new ArrayList(2); Collections.addAll(result, key, value); offset.increment(reader.syncSeen(), reader.getPosition()); return result; } return null; } @Override public void close() { try { reader.close(); } catch (IOException e) { LOG.warn("Ignoring error when closing file " + getFilePath(), e); } } public Offset getFileOffset() { return offset; } public static class Offset implements FileOffset { public long lastSyncPoint; public long recordsSinceLastSync; public long currentRecord; private long currRecordEndOffset; private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if (offset == null) { throw new IllegalArgumentException("offset cannot be null"); } if (offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if (rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord + 1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if (currentRecord < rhs.currentRecord) { return -1; } if (currentRecord == rhs.currentRecord) { return 0; } return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Offset)) { return false; } Offset offset = (Offset) o; return currentRecord == offset.currentRecord; } @Override public int hashCode() { return (int) (currentRecord ^ (currentRecord >>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if (!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | Feature envy | t | f | f | .Feature envy | blob | 0 | 14125 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/SequenceFileReader.java/#L28-L209 | 2 | 2319 | 14125 | minor |
| 2207 | { "output": "YES I found bad smells. The bad smells are: 1. Long method" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13515 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 2 | 2207 | 13515 | minor |
| 481 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 4700 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 2 | 481 | 4700 | major |
| 1762 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11892 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 | 1 | 1762 | 11892 | minor |
| 3331 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6212 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 1 | 3331 | 6212 | minor |
| 679 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BeanIOIterator implements Iterator, Closeable { private BeanReader reader; private transient Object next; private transient Object forceNext; public BeanIOIterator(BeanReader reader) { this.reader = reader; this.next = next(); } @Override public void close() throws IOException { if (reader != null) { reader.close(); reader = null; } } @Override public boolean hasNext() { return next != null; } @Override public Object next() { Object answer = next; if (answer == null) { answer = reader.read(); // after read we may force a next if (forceNext != null) { answer = forceNext; forceNext = null; } } else { next = reader.read(); // after read we may force a next if (forceNext != null) { next = forceNext; forceNext = null; } } return answer; } @Override public void remove() { // noop } /** * Sets a custom object as the next, such as from a custom error handler */ public void setNext(Object next) { this.forceNext = next; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6586 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-beanio/src/main/java/org/apache/camel/dataformat/beanio/BeanIOIterator.java/#L25-L81 | 2 | 679 | 6586 | minor |
| 329 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3387 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 2 | 329 | 3387 | major |
| 5004 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13760 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5004 | 13760 | major | ||
| 404 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | long method | t | t | f | long method | blob | 0 | 4119 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 404 | 4119 | minor |
| 1493 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11121 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 1 | 1493 | 11121 | minor |
| 453 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class DocumentsWriterDeleteQueue implements Accountable { // the current end (latest delete operation) in the delete queue: private volatile Node tail; /** Used to record deletes against all prior (already written to disk) segments. Whenever any segment flushes, we bundle up this set of * deletes and insert into the buffered updates stream before the newly flushed segment(s). */ private final DeleteSlice globalSlice; private final BufferedUpdates globalBufferedUpdates; // only acquired to update the global deletes, pkg-private for access by tests: final ReentrantLock globalBufferLock = new ReentrantLock(); final long generation; /** Generates the sequence number that IW returns to callers changing the index, showing the effective serialization of all operations. */ private final AtomicLong nextSeqNo; private final InfoStream infoStream; // for asserts long maxSeqNo = Long.MAX_VALUE; DocumentsWriterDeleteQueue(InfoStream infoStream) { // seqNo must start at 1 because some APIs negate this to also return a boolean this(infoStream, 0, 1); } DocumentsWriterDeleteQueue(InfoStream infoStream, long generation, long startSeqNo) { this(infoStream, new BufferedUpdates("global"), generation, startSeqNo); } DocumentsWriterDeleteQueue(InfoStream infoStream, BufferedUpdates globalBufferedUpdates, long generation, long startSeqNo) { this.infoStream = infoStream; this.globalBufferedUpdates = globalBufferedUpdates; this.generation = generation; this.nextSeqNo = new AtomicLong(startSeqNo); /* * we use a sentinel instance as our initial tail. No slice will ever try to * apply this tail since the head is always omitted. */ tail = new Node<>(null); // sentinel globalSlice = new DeleteSlice(tail); } long addDelete(Query... queries) { long seqNo = add(new QueryArrayNode(queries)); tryApplyGlobalSlice(); return seqNo; } long addDelete(Term... terms) { long seqNo = add(new TermArrayNode(terms)); tryApplyGlobalSlice(); return seqNo; } long addDocValuesUpdates(DocValuesUpdate... updates) { long seqNo = add(new DocValuesUpdatesNode(updates)); tryApplyGlobalSlice(); return seqNo; } static Node newNode(Term term) { return new TermNode(term); } static Node newNode(DocValuesUpdate... updates) { return new DocValuesUpdatesNode(updates); } /** * invariant for document update */ long add(Node deleteNode, DeleteSlice slice) { long seqNo = add(deleteNode); /* * this is an update request where the term is the updated documents * delTerm. in that case we need to guarantee that this insert is atomic * with regards to the given delete slice. This means if two threads try to * update the same document with in turn the same delTerm one of them must * win. By taking the node we have created for our del term as the new tail * it is guaranteed that if another thread adds the same right after us we * will apply this delete next time we update our slice and one of the two * competing updates wins! */ slice.sliceTail = deleteNode; assert slice.sliceHead != slice.sliceTail : "slice head and tail must differ after add"; tryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe // we can do it just every n times or so? return seqNo; } synchronized long add(Node newNode) { tail.next = newNode; this.tail = newNode; return getNextSequenceNumber(); } boolean anyChanges() { globalBufferLock.lock(); try { /* * check if all items in the global slice were applied * and if the global slice is up-to-date * and if globalBufferedUpdates has changes */ return globalBufferedUpdates.any() || !globalSlice.isEmpty() || globalSlice.sliceTail != tail || tail.next != null; } finally { globalBufferLock.unlock(); } } void tryApplyGlobalSlice() { if (globalBufferLock.tryLock()) { /* * The global buffer must be locked but we don't need to update them if * there is an update going on right now. It is sufficient to apply the * deletes that have been added after the current in-flight global slices * tail the next time we can get the lock! */ try { if (updateSliceNoSeqNo(globalSlice)) { globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } } finally { globalBufferLock.unlock(); } } } FrozenBufferedUpdates freezeGlobalBuffer(DeleteSlice callerSlice) throws IOException { globalBufferLock.lock(); /* * Here we freeze the global buffer so we need to lock it, apply all * deletes in the queue and reset the global slice to let the GC prune the * queue. */ final Node currentTail = tail; // take the current tail make this local any // Changes after this call are applied later // and not relevant here if (callerSlice != null) { // Update the callers slices so we are on the same page callerSlice.sliceTail = currentTail; } try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } if (globalBufferedUpdates.any()) { final FrozenBufferedUpdates packet = new FrozenBufferedUpdates(infoStream, globalBufferedUpdates, null); globalBufferedUpdates.clear(); return packet; } else { return null; } } finally { globalBufferLock.unlock(); } } DeleteSlice newSlice() { return new DeleteSlice(tail); } /** Negative result means there were new deletes since we last applied */ synchronized long updateSlice(DeleteSlice slice) { long seqNo = getNextSequenceNumber(); if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; seqNo = -seqNo; } return seqNo; } /** Just like updateSlice, but does not assign a sequence number */ boolean updateSliceNoSeqNo(DeleteSlice slice) { if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; return true; } return false; } static class DeleteSlice { // No need to be volatile, slices are thread captive (only accessed by one thread)! Node sliceHead; // we don't apply this one Node sliceTail; DeleteSlice(Node currentTail) { assert currentTail != null; /* * Initially this is a 0 length slice pointing to the 'current' tail of * the queue. Once we update the slice we only need to assign the tail and * have a new slice */ sliceHead = sliceTail = currentTail; } void apply(BufferedUpdates del, int docIDUpto) { if (sliceHead == sliceTail) { // 0 length slice return; } /* * When we apply a slice we take the head and get its next as our first * item to apply and continue until we applied the tail. If the head and * tail in this slice are not equal then there will be at least one more * non-null node in the slice! */ Node current = sliceHead; do { current = current.next; assert current != null : "slice property violated between the head on the tail must not be a null node"; current.apply(del, docIDUpto); } while (current != sliceTail); reset(); } void reset() { // Reset to a 0 length slice sliceHead = sliceTail; } /** * Returns true iff the given node is identical to the the slices tail, * otherwise false. */ boolean isTail(Node node) { return sliceTail == node; } /** * Returns true iff the given item is identical to the item * hold by the slices tail, otherwise false. */ boolean isTailItem(Object object) { return sliceTail.item == object; } boolean isEmpty() { return sliceHead == sliceTail; } } public int numGlobalTermDeletes() { return globalBufferedUpdates.numTermDeletes.get(); } void clear() { globalBufferLock.lock(); try { final Node currentTail = tail; globalSlice.sliceHead = globalSlice.sliceTail = currentTail; globalBufferedUpdates.clear(); } finally { globalBufferLock.unlock(); } } static class Node { volatile Node next; final T item; Node(T item) { this.item = item; } void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { throw new IllegalStateException("sentinel item must never be applied"); } boolean isDelete() { return true; } } private static final class TermNode extends Node { TermNode(Term term) { super(term); } @Override void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { bufferedDeletes.addTerm(item, docIDUpto); } @Override public String toString() { return "del=" + item; } } private static final class QueryArrayNode extends Node { QueryArrayNode(Query[] query) { super(query); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Query query : item) { bufferedUpdates.addQuery(query, docIDUpto); } } } private static final class TermArrayNode extends Node { TermArrayNode(Term[] term) { super(term); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Term term : item) { bufferedUpdates.addTerm(term, docIDUpto); } } @Override public String toString() { return "dels=" + Arrays.toString(item); } } private static final class DocValuesUpdatesNode extends Node { DocValuesUpdatesNode(DocValuesUpdate... updates) { super(updates); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (DocValuesUpdate update : item) { switch (update.type) { case NUMERIC: bufferedUpdates.addNumericUpdate((NumericDocValuesUpdate) update, docIDUpto); break; case BINARY: bufferedUpdates.addBinaryUpdate((BinaryDocValuesUpdate) update, docIDUpto); break; default: throw new IllegalArgumentException(update.type + " DocValues updates not supported yet!"); } } } @Override boolean isDelete() { return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("docValuesUpdates: "); if (item.length > 0) { sb.append("term=").append(item[0].term).append("; updates: ["); for (DocValuesUpdate update : item) { sb.append(update.field).append(':').append(update.valueToString()).append(','); } sb.setCharAt(sb.length()-1, ']'); } return sb.toString(); } } private boolean forceApplyGlobalSlice() { globalBufferLock.lock(); final Node currentTail = tail; try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } return globalBufferedUpdates.any(); } finally { globalBufferLock.unlock(); } } public int getBufferedUpdatesTermsSize() { globalBufferLock.lock(); try { forceApplyGlobalSlice(); return globalBufferedUpdates.deleteTerms.size(); } finally { globalBufferLock.unlock(); } } @Override public long ramBytesUsed() { return globalBufferedUpdates.ramBytesUsed(); } @Override public String toString() { return "DWDQ: [ generation: " + generation + " ]"; } public long getNextSequenceNumber() { long seqNo = nextSeqNo.getAndIncrement(); assert seqNo < maxSeqNo: "seqNo=" + seqNo + " vs maxSeqNo=" + maxSeqNo; return seqNo; } public long getLastSequenceNumber() { return nextSeqNo.get()-1; } /** Inserts a gap in the sequence numbers. This is used by IW during flush or commit to ensure any in-flight threads get sequence numbers * inside the gap */ public void skipSequenceNumbers(long jump) { nextSeqNo.addAndGet(jump); } } |
blob | long method | t | t | f | long method | blob | 0 | 4437 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java/#L71-L495 | 1 | 453 | 4437 | major |
| 2063 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12977 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 1 | 2063 | 12977 | minor |
| 479 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 4625 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 1 | 479 | 4625 | minor |
| 1479 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 11069 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 1479 | 11069 | minor |
| 691 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Commented out code, 4. Dead code, 5. Magic numbers, 6. Inconsistent formatting, 7. Unnecessary explicit scoping, 8. Inefficient use of data structures, 9. Unnecessary synchronized blocks, 10. Nested try-catch blocks, 11. Use of boolean flags to control program flow, 12. Use of null checks, 13. Misleading variable names, 14. Unused variables, 15. Inconsistent and confusing use of braces, 16. Use of anonymous classes, 17. Mix of Java concurrency APIs, 18. Hard-coded logger statements instead of using a logging framework, 19. Unnecessary checked exception handling, 20. Inconsistent and unclear comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | Long method, 2 Feature envy, 3 Commented out code, 4 Dead code, 5 Magic numbers, 6 Inconsistent formatting, 7 Unnecessary explicit scoping, 8 Inefficient use of data structures, 9 Unnecessary synchronized blocks, | t | f | f | . Long method, 2. Feature envy, 3. Commented out code, 4. Dead code, 5. Magic numbers, 6. Inconsistent formatting, 7. Unnecessary explicit scoping, 8. Inefficient use of data structures, 9. Unnecessary synchronized blocks, | blob | 0 | 6652 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 2 | 691 | 6652 | major |
| 1055 | YES, I found bad smells, the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XmiWriterCasConsumer extends CasConsumer_ImplBase { /** * Name of configuration parameter that must be set to the path of a directory into which the * output files will be written. */ public static final String PARAM_OUTPUTDIR = "OutputDirectory"; private File mOutputDir; private int mDocNum; public void initialize() throws ResourceInitializationException { mDocNum = 0; mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * Processes the CAS which was populated by the TextAnalysisEngines. * In this case, the CAS is converted to XMI and written into the output file . * * @param aCAS * a CAS which has been populated by the TAEs * * @throws ResourceProcessException * if there is an error in processing the Resource * * @see org.apache.uima.collection.base_cpm.CasObjectProcessor#processCas(org.apache.uima.cas.CAS) */ public void processCas(CAS aCAS) throws ResourceProcessException { String modelFileName = null; JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // retrieve the filename of the input file from the CAS FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator(); File outFile = null; if (it.hasNext()) { SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next(); File inFile; try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += ".xmi"; outFile = new File(mOutputDir, outFileName); modelFileName = mOutputDir.getAbsolutePath() + "/" + inFile.getName() + ".ecore"; } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xmi"); } // serialize XCAS and write to output file try { writeXmi(jcas.getCas(), outFile, modelFileName); } catch (IOException e) { throw new ResourceProcessException(e); } catch (SAXException e) { throw new ResourceProcessException(e); } } /** * Serialize a CAS to a file in XMI format * * @param aCas * CAS to serialize * @param name * output file * @throws SAXException - * @throws Exception - * * @throws ResourceProcessException - */ private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException { FileOutputStream out = null; try { // write XMI out = new FileOutputStream(name); XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(out, false); ser.serialize(aCas, xmlSer.getContentHandler()); } finally { if (out != null) { out.close(); } } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 9506 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-examples/src/main/java/org/apache/uima/examples/xmi/XmiWriterCasConsumer.java/#L48-L148 | 2 | 1055 | 9506 | minor |
| 1199 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10278 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 1199 | 10278 | major |
| 2610 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 15035 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 2 | 2610 | 15035 | minor |
| 4308 | YES, I found bad smells in the line below:1.Long method,2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method,2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11355 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 4308 | 11355 | minor |
| 3823 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 9798 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L54340-L54409 | 2 | 3823 | 9798 | minor | ||
| 424 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4255 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 1 | 424 | 4255 | major |
| 2090 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BatchWriterReplicationReplayer implements AccumuloReplicationReplayer { private static final Logger log = LoggerFactory.getLogger(BatchWriterReplicationReplayer.class); @Override public long replicateLog(ClientContext context, String tableName, WalEdits data) throws RemoteReplicationException { final LogFileKey key = new LogFileKey(); final LogFileValue value = new LogFileValue(); final long memoryInBytes = context.getConfiguration() .getAsBytes(Property.TSERV_REPLICATION_BW_REPLAYER_MEMORY); BatchWriter bw = null; long mutationsApplied = 0L; try { for (ByteBuffer edit : data.getEdits()) { DataInputStream dis = new DataInputStream(ByteBufferUtil.toByteArrayInputStream(edit)); try { key.readFields(dis); // TODO this is brittle because AccumuloReplicaSystem isn't actually calling // LogFileValue.write, but we're expecting // what we receive to be readable by the LogFileValue. value.readFields(dis); } catch (IOException e) { log.error("Could not deserialize edit from stream", e); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_DESERIALIZE, "Could not deserialize edit from stream"); } // Create the batchScanner if we don't already have one. if (bw == null) { BatchWriterConfig bwConfig = new BatchWriterConfig(); bwConfig.setMaxMemory(memoryInBytes); try { bw = context.createBatchWriter(tableName, bwConfig); } catch (TableNotFoundException e) { throw new RemoteReplicationException(RemoteReplicationErrorCode.TABLE_DOES_NOT_EXIST, "Table " + tableName + " does not exist"); } } log.info("Applying {} mutations to table {} as part of batch", value.mutations.size(), tableName); // If we got a ServerMutation, we have to make sure that we preserve the systemTimestamp // otherwise // the local system will assign a new timestamp. List mutationsCopy = new ArrayList<>(value.mutations.size()); long mutationsCopied = 0L; for (Mutation orig : value.mutations) { if (orig instanceof ServerMutation) { mutationsCopied++; ServerMutation origServer = (ServerMutation) orig; Mutation copy = new Mutation(orig.getRow()); for (ColumnUpdate update : orig.getUpdates()) { long timestamp; // If the update doesn't have a timestamp, pull it from the ServerMutation if (!update.hasTimestamp()) { timestamp = origServer.getSystemTimestamp(); } else { timestamp = update.getTimestamp(); } // TODO ACCUMULO-2937 cache the CVs if (update.isDeleted()) { copy.putDelete(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp); } else { copy.put(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp, update.getValue()); } } // We also need to preserve the replicationSource information to prevent cycles Set replicationSources = orig.getReplicationSources(); if (replicationSources != null && !replicationSources.isEmpty()) { for (String replicationSource : replicationSources) { copy.addReplicationSource(replicationSource); } } mutationsCopy.add(copy); } else { mutationsCopy.add(orig); } } log.debug("Copied {} mutations to ensure server-assigned timestamps are propagated", mutationsCopied); try { bw.addMutations(mutationsCopy); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } log.debug("{} mutations added to the BatchScanner", mutationsCopy.size()); mutationsApplied += mutationsCopy.size(); } } finally { if (bw != null) { try { bw.close(); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } } } log.info("Applied {} mutations in total to {}", mutationsApplied, tableName); return mutationsApplied; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13120 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/tserver/src/main/java/org/apache/accumulo/tserver/replication/BatchWriterReplicationReplayer.java/#L50-L171 | 1 | 2090 | 13120 | minor |
| 3966 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 10400 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 2 | 3966 | 10400 | minor | ||
| 27 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 704 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 2 | 27 | 704 | major |
| 328 | YES, I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3385 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 2 | 328 | 3385 | minor |
| 2230 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13584 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 2230 | 13584 | minor |
| 421 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 4241 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 1 | 421 | 4241 | major |
| 699 | YES, I found bad smells.The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else if ( (LA12_0=='\'') ) {s = 10;} else if ( (LA12_0=='/') ) {s = 11;} else if ( ((LA12_0>='\t' && LA12_0<='\n')||LA12_0=='\r'||LA12_0==' ') ) {s = 12;} else if ( ((LA12_0>='\u0000' && LA12_0<='\b')||(LA12_0>='\u000B' && LA12_0<='\f')||(LA12_0>='\u000E' && LA12_0<='\u001F')||LA12_0=='!'||(LA12_0>='#' && LA12_0<='&')||(LA12_0>='(' && LA12_0<='.')||(LA12_0>=':' && LA12_0<='@')||(LA12_0>='[' && LA12_0<=']')||LA12_0=='`'||(LA12_0>='{' && LA12_0<='\uFFFF')) ) {s = 13;} if ( s>=0 ) return s; break; case 1 : int LA12_9 = input.LA(1); s = -1; if ( ((LA12_9>='\u0000' && LA12_9<='\uFFFF')) ) {s = 22;} else s = 13; if ( s>=0 ) return s; break; case 2 : int LA12_10 = input.LA(1); s = -1; if ( ((LA12_10>='\u0000' && LA12_10<='\uFFFF')) ) {s = 22;} else s = 13; if ( s>=0 ) return s; break; } NoViableAltException nvae = new NoViableAltException(getDescription(), 12, _s, input); error(nvae); throw nvae; } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 6685 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.core.idea.tests/src-gen/org/eclipse/xtext/parser/assignments/idea/parser/antlr/internal/PsiInternalAssignmentsTestLanguageLexer.java/#L1126-L1204 | 2 | 699 | 6685 | minor |
| 1591 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupByMergingQueryRunnerV2 implements QueryRunner { private static final Logger log = new Logger(GroupByMergingQueryRunnerV2.class); private static final String CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION = "mergeRunnersUsingChainedExecution"; private final GroupByQueryConfig config; private final Iterable> queryables; private final ListeningExecutorService exec; private final QueryWatcher queryWatcher; private final int concurrencyHint; private final BlockingPool mergeBufferPool; private final ObjectMapper spillMapper; private final String processingTmpDir; private final int mergeBufferSize; public GroupByMergingQueryRunnerV2( GroupByQueryConfig config, ExecutorService exec, QueryWatcher queryWatcher, Iterable> queryables, int concurrencyHint, BlockingPool mergeBufferPool, int mergeBufferSize, ObjectMapper spillMapper, String processingTmpDir ) { this.config = config; this.exec = MoreExecutors.listeningDecorator(exec); this.queryWatcher = queryWatcher; this.queryables = Iterables.unmodifiableIterable(Iterables.filter(queryables, Predicates.notNull())); this.concurrencyHint = concurrencyHint; this.mergeBufferPool = mergeBufferPool; this.spillMapper = spillMapper; this.processingTmpDir = processingTmpDir; this.mergeBufferSize = mergeBufferSize; } @Override public Sequence run(final QueryPlus queryPlus, final Map responseContext) { final GroupByQuery query = (GroupByQuery) queryPlus.getQuery(); final GroupByQueryConfig querySpecificConfig = config.withOverrides(query); // CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION is here because realtime servers use nested mergeRunners calls // (one for the entire query and one for each sink). We only want the outer call to actually do merging with a // merge buffer, otherwise the query will allocate too many merge buffers. This is potentially sub-optimal as it // will involve materializing the results for each sink before starting to feed them into the outer merge buffer. // I'm not sure of a better way to do this without tweaking how realtime servers do queries. final boolean forceChainedExecution = query.getContextBoolean( CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, false ); final QueryPlus queryPlusForRunners = queryPlus .withQuery( query.withOverriddenContext(ImmutableMap.of(CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, true)) ) .withoutThreadUnsafeState(); if (QueryContexts.isBySegment(query) || forceChainedExecution) { ChainedExecutionQueryRunner runner = new ChainedExecutionQueryRunner<>(exec, queryWatcher, queryables); return runner.run(queryPlusForRunners, responseContext); } final boolean isSingleThreaded = querySpecificConfig.isSingleThreaded(); final AggregatorFactory[] combiningAggregatorFactories = new AggregatorFactory[query.getAggregatorSpecs().size()]; for (int i = 0; i < query.getAggregatorSpecs().size(); i++) { combiningAggregatorFactories[i] = query.getAggregatorSpecs().get(i).getCombiningFactory(); } final File temporaryStorageDirectory = new File( processingTmpDir, StringUtils.format("druid-groupBy-%s_%s", UUID.randomUUID(), query.getId()) ); final int priority = QueryContexts.getPriority(query); // Figure out timeoutAt time now, so we can apply the timeout to both the mergeBufferPool.take and the actual // query processing together. final long queryTimeout = QueryContexts.getTimeout(query); final boolean hasTimeout = QueryContexts.hasTimeout(query); final long timeoutAt = System.currentTimeMillis() + queryTimeout; return new BaseSequence<>( new BaseSequence.IteratorMaker>() { @Override public CloseableGrouperIterator make() { final List resources = new ArrayList<>(); try { final LimitedTemporaryStorage temporaryStorage = new LimitedTemporaryStorage( temporaryStorageDirectory, querySpecificConfig.getMaxOnDiskStorage() ); final ReferenceCountingResourceHolder temporaryStorageHolder = ReferenceCountingResourceHolder.fromCloseable(temporaryStorage); resources.add(temporaryStorageHolder); // If parallelCombine is enabled, we need two merge buffers for parallel aggregating and parallel combining final int numMergeBuffers = querySpecificConfig.getNumParallelCombineThreads() > 1 ? 2 : 1; final List> mergeBufferHolders = getMergeBuffersHolder( numMergeBuffers, hasTimeout, timeoutAt ); resources.addAll(mergeBufferHolders); final ReferenceCountingResourceHolder mergeBufferHolder = mergeBufferHolders.get(0); final ReferenceCountingResourceHolder combineBufferHolder = numMergeBuffers == 2 ? mergeBufferHolders.get(1) : null; Pair, Accumulator> pair = RowBasedGrouperHelper.createGrouperAccumulatorPair( query, false, null, config, Suppliers.ofInstance(mergeBufferHolder.get()), combineBufferHolder, concurrencyHint, temporaryStorage, spillMapper, combiningAggregatorFactories, exec, priority, hasTimeout, timeoutAt, mergeBufferSize ); final Grouper grouper = pair.lhs; final Accumulator accumulator = pair.rhs; grouper.init(); final ReferenceCountingResourceHolder> grouperHolder = ReferenceCountingResourceHolder.fromCloseable(grouper); resources.add(grouperHolder); ListenableFuture> futures = Futures.allAsList( Lists.newArrayList( Iterables.transform( queryables, new Function, ListenableFuture>() { @Override public ListenableFuture apply(final QueryRunner input) { if (input == null) { throw new ISE( "Null queryRunner! Looks to be some segment unmapping action happening" ); } ListenableFuture future = exec.submit( new AbstractPrioritizedCallable(priority) { @Override public AggregateResult call() { try ( // These variables are used to close releasers automatically. @SuppressWarnings("unused") Releaser bufferReleaser = mergeBufferHolder.increment(); @SuppressWarnings("unused") Releaser grouperReleaser = grouperHolder.increment() ) { final AggregateResult retVal = input.run(queryPlusForRunners, responseContext) .accumulate( AggregateResult.ok(), accumulator ); // Return true if OK, false if resources were exhausted. return retVal; } catch (QueryInterruptedException e) { throw e; } catch (Exception e) { log.error(e, "Exception with one of the sequences!"); throw new RuntimeException(e); } } } ); if (isSingleThreaded) { waitForFutureCompletion( query, Futures.allAsList(ImmutableList.of(future)), hasTimeout, timeoutAt - System.currentTimeMillis() ); } return future; } } ) ) ); if (!isSingleThreaded) { waitForFutureCompletion(query, futures, hasTimeout, timeoutAt - System.currentTimeMillis()); } return RowBasedGrouperHelper.makeGrouperIterator( grouper, query, new Closeable() { @Override public void close() { for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } } } ); } catch (Throwable e) { // Exception caught while setting up the iterator; release resources. for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } throw e; } } @Override public void cleanup(CloseableGrouperIterator iterFromMake) { iterFromMake.close(); } } ); } private List> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List> mergeBufferHolder; // This will potentially block if there are no merge buffers left in the pool. if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } } private void waitForFutureCompletion( GroupByQuery query, ListenableFuture> future, boolean hasTimeout, long timeout ) { try { if (queryWatcher != null) { queryWatcher.registerQuery(query, future); } if (hasTimeout && timeout <= 0) { throw new TimeoutException(); } final List results = hasTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get(); for (AggregateResult result : results) { if (!result.isOk()) { future.cancel(true); throw new ResourceLimitExceededException(result.getReason()); } } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (CancellationException e) { throw new QueryInterruptedException(e); } catch (TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } |
blob | t | f | f | blob | 0 | 11390 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/GroupByMergingQueryRunnerV2.java/#L72-L392 | 1 | 1591 | 11390 | critical | ||
| 2483 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | long method | t | t | f | long method | blob | 0 | 14602 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 1 | 2483 | 14602 | major |
| 2500 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14653 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2500 | 14653 | major |
| 1936 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12467 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 2 | 1936 | 12467 | major | ||
| 2162 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 13329 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 2162 | 13329 | major |
| 475 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4581 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 475 | 4581 | minor |
| 3348 | {"response": "YES I found bad smells", "detected bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6306 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 3348 | 6306 | major |
| 1998 | {} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | f | f | f | long method | 0 | 12702 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 1 | 1998 | 12702 | minor | ||
| 4734 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 12715 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 4734 | 12715 | critical |
| 541 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 5537 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 541 | 5537 | major |
| 3975 | YES I found bad smells The bad smells are: 1. Feature envy, 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Feature envy, 2 Long method | t | f | f | . Feature envy, 2. Long method | data class | 0 | 10430 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 3975 | 10430 | critical |
| 1304 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10672 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 2 | 1304 | 10672 | minor |
| 1696 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FunctionTagsTable extends Composite { private final FunctionEditorInput functionEditorInput; private final KeyValueSetEditingComposite tagsEditingComposite; private final KeyValueSetDataModel tagsDataModel; public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) { super(parent, SWT.NONE); this.functionEditorInput = functionEditorInput; this.setLayout(new GridLayout()); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList()); tagsEditingComposite = new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH))) .addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH))) .addKeyValidator(new LambdaTagNameValidator()) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSaveTags(); } }) .build(this, tagsDataModel); Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttonComposite.setLayout(new GridLayout(1, false)); refresh(); } public void refresh() { Map tagMap = functionEditorInput.getLambdaClient() .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); tagsDataModel.getPairSet().clear(); for (Entry entry : tagMap.entrySet()) { tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue())); } tagsEditingComposite.refresh(); } private void onSaveTags() { try { AWSLambda lambda = functionEditorInput.getLambdaClient(); Map oldTagMap = lambda .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); List tagKeysToBeRemoved = new ArrayList<>(); for (String key : oldTagMap.keySet()) { if (!tagsDataModel.getPairSet().contains(key)) { tagKeysToBeRemoved.add(key); } } Map tagMap = new HashMap<>(); for (Pair pair : tagsDataModel.getPairSet()) { tagMap.put(pair.getKey(), pair.getValue()); } if (!tagKeysToBeRemoved.isEmpty()) { lambda.untagResource(new UntagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTagKeys(tagKeysToBeRemoved)); } lambda.tagResource(new TagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTags(tagMap)); } catch (AWSLambdaException e) { LambdaPlugin.getDefault().reportException(e.getMessage(), e); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy. | blob | 0 | 11720 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.java/#L47-L123 | 2 | 1696 | 11720 | minor |
| 1404 | { "response": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 10872 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 1404 | 10872 | major |
| 1916 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12408 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 1916 | 12408 | minor |
| 2069 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | f | f | f | data class | 0 | 13004 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 2069 | 13004 | major | ||
| 1386 | YES I found bad smells the bad smells are: 1) Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | )Long method | t | f | f | )Long method | data class | 0 | 10834 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 1386 | 10834 | critical |
| 389 | YES I found bad smells the bad smells are: 1.Long method 2. Unnecessary if/else statements 3. Duplicated code 4. Magic numbers/string literals 5. Lack of comments/documentation 6. Inconsistent formatting 7. Use of HashMap instead of more specific data structure 8. Unused constructor | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XPathParser { private final Map prefixes = new HashMap(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // for compatibility return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } } |
blob | Long method2 Unnecessary if/else statements3 Duplicated code4 Magic numbers/string literals5 Lack of comments/documentation6 Inconsistent formatting7 Use of HashMap instead of more specific data structure8 Unused constructor | t | f | f | .Long method2. Unnecessary if/else statements3. Duplicated code4. Magic numbers/string literals5. Lack of comments/documentation6. Inconsistent formatting7. Use of HashMap instead of more specific data structure8. Unused constructor | blob | 0 | 3948 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/sax/xpath/XPathParser.java/#L40-L120 | 2 | 389 | 3948 | minor |
| 1144 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JavadocFormatter { private static final String CODE_RESET = "\033[0m"; private static final String CODE_HIGHLIGHT = "\033[1m"; private static final String CODE_UNDERLINE = "\033[4m"; private final int lineLimit; private final boolean escapeSequencesSupported; /** Construct the formatter. * * @param lineLimit maximum line length * @param escapeSequencesSupported whether escape sequences are supported */ public JavadocFormatter(int lineLimit, boolean escapeSequencesSupported) { this.lineLimit = lineLimit; this.escapeSequencesSupported = escapeSequencesSupported; } private static final int MAX_LINE_LENGTH = 95; private static final int SHORTEST_LINE = 30; private static final int INDENT = 4; /**Format javadoc to plain text. * * @param header element caption that should be used * @param javadoc to format * @return javadoc formatted to plain text */ public String formatJavadoc(String header, String javadoc) { try { StringBuilder result = new StringBuilder(); result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n"); if (javadoc == null) { return result.toString(); } JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null); DocTrees trees = DocTrees.instance(task); DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) { @Override @DefinedBy(Api.COMPILER) public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "" + javadoc + ""; } }); new FormatJavadocScanner(result, task).scan(docComment, null); addNewLineIfNeeded(result); return result.toString(); } catch (URISyntaxException ex) { throw new InternalError("Unexpected exception", ex); } } private class FormatJavadocScanner extends DocTreeScanner { private final StringBuilder result; private final JavacTask task; private int reflownTo; private int indent; private int limit = Math.min(lineLimit, MAX_LINE_LENGTH); private boolean pre; private Map tableColumns; public FormatJavadocScanner(StringBuilder result, JavacTask task) { this.result = result; this.task = task; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitDocComment(DocCommentTree node, Object p) { tableColumns = countTableColumns(node); reflownTo = result.length(); scan(node.getFirstSentence(), p); scan(node.getBody(), p); reflow(result, reflownTo, indent, limit); for (Sections current : docSections.keySet()) { boolean seenAny = false; for (DocTree t : node.getBlockTags()) { if (current.matches(t)) { if (!seenAny) { seenAny = true; if (result.charAt(result.length() - 1) != '\n') result.append("\n"); result.append("\n"); result.append(escape(CODE_UNDERLINE)) .append(docSections.get(current)) .append(escape(CODE_RESET)) .append("\n"); } scan(t, null); } } } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitText(TextTree node, Object p) { String text = node.getBody(); if (!pre) { text = text.replaceAll("[ \t\r\n]+", " ").trim(); if (text.isEmpty()) { text = " "; } } else { text = text.replaceAll("\n", "\n" + indentString(indent)); } result.append(text); return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLink(LinkTree node, Object p) { if (!node.getLabel().isEmpty()) { scan(node.getLabel(), p); } else { result.append(node.getReference().getSignature()); } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitParam(ParamTree node, Object p) { return formatDef(node.getName().getName(), node.getDescription()); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitThrows(ThrowsTree node, Object p) { return formatDef(node.getExceptionName().getSignature(), node.getDescription()); } public Object formatDef(CharSequence name, List description) { result.append(name); result.append(" - "); reflownTo = result.length(); indent = name.length() + 3; if (limit - indent < SHORTEST_LINE) { result.append("\n"); result.append(indentString(INDENT)); indent = INDENT; reflownTo += INDENT; } try { return scan(description, null); } finally { reflow(result, reflownTo, indent, limit); result.append("\n"); } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLiteral(LiteralTree node, Object p) { return scan(node.getBody(), p); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitReturn(ReturnTree node, Object p) { reflownTo = result.length(); try { return super.visitReturn(node, p); } finally { reflow(result, reflownTo, 0, limit); } } Stack listStack = new Stack<>(); Stack defStack = new Stack<>(); Stack tableStack = new Stack<>(); Stack> cellsStack = new Stack<>(); Stack> headerStack = new Stack<>(); @Override @DefinedBy(Api.COMPILER_TREE) public Object visitStartElement(StartElementTree node, Object p) { switch (getHtmlTag(node.getName())) { case P: if (lastNode!= null && lastNode.getKind() == DocTree.Kind.START_ELEMENT && HtmlTag.get(((StartElementTree) lastNode).getName()) == HtmlTag.LI) { //ignore break; } reflowTillNow(); addNewLineIfNeeded(result); result.append(indentString(indent)); reflownTo = result.length(); break; case BLOCKQUOTE: reflowTillNow(); indent += INDENT; break; case PRE: reflowTillNow(); pre = true; break; case UL: reflowTillNow(); listStack.push(-1); indent += INDENT; break; case OL: reflowTillNow(); listStack.push(1); indent += INDENT; break; case DL: reflowTillNow(); defStack.push(indent); break; case LI: reflowTillNow(); if (!listStack.empty()) { addNewLineIfNeeded(result); int top = listStack.pop(); if (top == (-1)) { result.append(indentString(indent - 2)); result.append("* "); } else { result.append(indentString(indent - 3)); result.append("" + top++ + ". "); } listStack.push(top); reflownTo = result.length(); } break; case DT: reflowTillNow(); if (!defStack.isEmpty()) { addNewLineIfNeeded(result); indent = defStack.peek(); result.append(escape(CODE_HIGHLIGHT)); } break; case DD: reflowTillNow(); if (!defStack.isEmpty()) { if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } addNewLineIfNeeded(result); indent = defStack.peek() + INDENT; result.append(indentString(indent)); } break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); addNewLineIfNeeded(result); result.append("\n") .append(escape(CODE_UNDERLINE)); reflownTo = result.length(); break; case TABLE: int columns = tableColumns.get(node); if (columns == 0) { break; //broken input } reflowTillNow(); addNewLineIfNeeded(result); reflownTo = result.length(); tableStack.push(limit); limit = (limit - 1) / columns - 3; for (int sep = 0; sep < (limit + 3) * columns + 1; sep++) { result.append("-"); } result.append("\n"); break; case TR: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(node.getName()); } cellsStack.push(new ArrayList<>()); headerStack.push(new ArrayList<>()); break; case TH: case TD: if (cellsStack.isEmpty()) { //broken code break; } reflowTillNow(); result.append("\n"); reflownTo = result.length(); cellsStack.peek().add(result.length()); headerStack.peek().add(HtmlTag.get(node.getName()) == HtmlTag.TH); break; case IMG: for (DocTree attr : node.getAttributes()) { if (attr.getKind() != DocTree.Kind.ATTRIBUTE) { continue; } AttributeTree at = (AttributeTree) attr; if ("alt".equals(StringUtils.toLowerCase(at.getName().toString()))) { addSpaceIfNeeded(result); scan(at.getValue(), null); addSpaceIfNeeded(result); break; } } break; default: addSpaceIfNeeded(result); break; } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEndElement(EndElementTree node, Object p) { handleEndElement(node.getName()); return super.visitEndElement(node, p); } private void handleEndElement(Name name) { switch (getHtmlTag(name)) { case BLOCKQUOTE: indent -= INDENT; break; case PRE: pre = false; addNewLineIfNeeded(result); reflownTo = result.length(); break; case UL: case OL: if (listStack.isEmpty()) { //ignore stray closing tag break; } reflowTillNow(); listStack.pop(); indent -= INDENT; addNewLineIfNeeded(result); break; case DL: if (defStack.isEmpty()) {//ignore stray closing tag break; } reflowTillNow(); if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } indent = defStack.pop(); addNewLineIfNeeded(result); break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); result.append(escape(CODE_RESET)) .append("\n"); reflownTo = result.length(); break; case TABLE: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(task.getElements().getName("tr")); } if (tableStack.isEmpty()) { break; } limit = tableStack.pop(); break; case TR: if (cellsStack.isEmpty()) { break; } reflowTillNow(); List cells = cellsStack.pop(); List headerFlags = headerStack.pop(); List content = new ArrayList<>(); int maxLines = 0; result.append("\n"); while (!cells.isEmpty()) { int currentCell = cells.remove(cells.size() - 1); String[] lines = result.substring(currentCell, result.length()).split("\n"); result.delete(currentCell - 1, result.length()); content.add(lines); maxLines = Math.max(maxLines, lines.length); } Collections.reverse(content); for (int line = 0; line < maxLines; line++) { for (int column = 0; column < content.size(); column++) { String[] lines = content.get(column); String currentLine = line < lines.length ? lines[line] : ""; result.append("| "); boolean header = headerFlags.get(column); if (header) { result.append(escape(CODE_HIGHLIGHT)); } result.append(currentLine); if (header) { result.append(escape(CODE_RESET)); } int padding = limit - currentLine.length(); if (padding > 0) result.append(indentString(padding)); result.append(" "); } result.append("|\n"); } for (int sep = 0; sep < (limit + 3) * content.size() + 1; sep++) { result.append("-"); } result.append("\n"); reflownTo = result.length(); break; case TD: case TH: break; default: addSpaceIfNeeded(result); break; } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEntity(EntityTree node, Object p) { String name = node.getName().toString(); int code = -1; if (name.startsWith("#")) { try { int v = StringUtils.toLowerCase(name).startsWith("#x") ? Integer.parseInt(name.substring(2), 16) : Integer.parseInt(name.substring(1), 10); if (Entity.isValid(v)) { code = v; } } catch (NumberFormatException ex) { //ignore } } else { Entity entity = Entity.get(name); if (entity != null) { code = entity.code; } } if (code != (-1)) { result.appendCodePoint(code); } else { result.append(node.toString()); } return super.visitEntity(node, p); } private DocTree lastNode; @Override @DefinedBy(Api.COMPILER_TREE) public Object scan(DocTree node, Object p) { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } try { return super.scan(node, p); } finally { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } lastNode = node; } } private void reflowTillNow() { while (result.length() > 0 && result.charAt(result.length() - 1) == ' ') result.delete(result.length() - 1, result.length()); reflow(result, reflownTo, indent, limit); reflownTo = result.length(); } }; private String escape(String sequence) { return this.escapeSequencesSupported ? sequence : ""; } private static final Map docSections = new LinkedHashMap<>(); static { ResourceBundle bundle = ResourceBundle.getBundle("jdk.internal.shellsupport.doc.resources.javadocformatter"); docSections.put(Sections.TYPE_PARAMS, bundle.getString("CAP_TypeParameters")); docSections.put(Sections.PARAMS, bundle.getString("CAP_Parameters")); docSections.put(Sections.RETURNS, bundle.getString("CAP_Returns")); docSections.put(Sections.THROWS, bundle.getString("CAP_Thrown_Exceptions")); } private static String indentString(int indent) { char[] content = new char[indent]; Arrays.fill(content, ' '); return new String(content); } private static void reflow(StringBuilder text, int from, int indent, int limit) { int lineStart = from; while (lineStart > 0 && text.charAt(lineStart - 1) != '\n') { lineStart--; } int lineChars = from - lineStart; int pointer = from; int lastSpace = -1; while (pointer < text.length()) { if (text.charAt(pointer) == ' ') lastSpace = pointer; if (lineChars >= limit) { if (lastSpace != (-1)) { text.setCharAt(lastSpace, '\n'); text.insert(lastSpace + 1, indentString(indent)); lineChars = indent + pointer - lastSpace - 1; pointer += indent; lastSpace = -1; } } lineChars++; pointer++; } } private static void addNewLineIfNeeded(StringBuilder text) { if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') { text.append("\n"); } } private static void addSpaceIfNeeded(StringBuilder text) { if (text.length() == 0) return ; char last = text.charAt(text.length() - 1); if (last != ' ' && last != '\n') { text.append(" "); } } private static HtmlTag getHtmlTag(Name name) { HtmlTag tag = HtmlTag.get(name); return tag != null ? tag : HtmlTag.HTML; //using HtmlTag.HTML as default no-op value } private static Map countTableColumns(DocCommentTree dct) { Map result = new IdentityHashMap<>(); new DocTreeScanner() { private StartElementTree currentTable; private int currentMaxColumns; private int currentRowColumns; @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { switch (getHtmlTag(node.getName())) { case TABLE: currentTable = node; break; case TR: currentMaxColumns = Math.max(currentMaxColumns, currentRowColumns); currentRowColumns = 0; break; case TD: case TH: currentRowColumns++; break; } return super.visitStartElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitEndElement(EndElementTree node, Void p) { if (HtmlTag.get(node.getName()) == HtmlTag.TABLE) { closeTable(); } return super.visitEndElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitDocComment(DocCommentTree node, Void p) { try { return super.visitDocComment(node, p); } finally { closeTable(); } } private void closeTable() { if (currentTable != null) { result.put(currentTable, Math.max(currentMaxColumns, currentRowColumns)); currentTable = null; } } }.scan(dct, null); return result; } private enum Sections { TYPE_PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && ((ParamTree) t).isTypeParameter(); } }, PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && !((ParamTree) t).isTypeParameter(); } }, RETURNS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.RETURN; } }, THROWS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.THROWS; } }; public abstract boolean matches(DocTree t); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10107 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java/#L70-L712 | 1 | 1144 | 10107 | critical |
| 2563 | {"YES I found bad smells":"the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExplainTask extends Task implements Serializable { public static final String STAGE_DEPENDENCIES = "STAGE DEPENDENCIES"; private static final long serialVersionUID = 1L; public static final String EXPL_COLUMN_NAME = "Explain"; private final Set> visitedOps = new HashSet>(); private boolean isLogical = false; protected final Logger LOG; public ExplainTask() { super(); LOG = LoggerFactory.getLogger(this.getClass().getName()); } /* * Below method returns the dependencies for the passed in query to EXPLAIN. * The dependencies are the set of input tables and partitions, and are * provided back as JSON output for the EXPLAIN command. * Example output: * {"input_tables":[{"tablename": "default@test_sambavi_v1", "tabletype": "TABLE"}], * "input partitions":["default@srcpart@ds=2008-04-08/hr=11"]} */ @VisibleForTesting static JSONObject getJSONDependencies(ExplainWork work) throws Exception { assert(work.getDependency()); JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); JSONArray inputTableInfo = new JSONArray(); JSONArray inputPartitionInfo = new JSONArray(); for (ReadEntity input: work.getInputs()) { switch (input.getType()) { case TABLE: Table table = input.getTable(); JSONObject tableInfo = new JSONObject(); tableInfo.put("tablename", table.getCompleteName()); tableInfo.put("tabletype", table.getTableType().toString()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { tableInfo.put("tableParents", input.getParents().toString()); } inputTableInfo.put(tableInfo); break; case PARTITION: JSONObject partitionInfo = new JSONObject(); partitionInfo.put("partitionName", input.getPartition().getCompleteName()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { partitionInfo.put("partitionParents", input.getParents().toString()); } inputPartitionInfo.put(partitionInfo); break; default: break; } } outJSONObject.put("input_tables", inputTableInfo); outJSONObject.put("input_partitions", inputPartitionInfo); return outJSONObject; } public JSONObject getJSONCBOPlan(PrintStream out, ExplainWork work) throws Exception { JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); String cboPlan = work.getCboPlan(); if (cboPlan != null) { if (jsonOutput) { outJSONObject.put("CBOPlan", cboPlan); } else { out.println("CBO PLAN:"); out.println(cboPlan); } } return outJSONObject; } public JSONObject getJSONLogicalPlan(PrintStream out, ExplainWork work) throws Exception { isLogical = true; JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } if (work.getParseContext() != null) { if (out != null) { out.print("LOGICAL PLAN:"); } JSONObject jsonPlan = outputMap(work.getParseContext().getTopOps(), true, out, work.getExtended(), jsonOutput, 0); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("LOGICAL PLAN", jsonPlan); } } else { System.err.println("No parse context!"); } return outJSONObject; } private static String trueCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS true"; private static String falseCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS false"; @VisibleForTesting ImmutablePair outputPlanVectorization(PrintStream out, boolean jsonOutput) throws Exception { if (out != null) { out.println("PLAN VECTORIZATION:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; HiveConf hiveConf = queryState.getConf(); boolean isVectorizationEnabled = HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED); String isVectorizationEnabledCondName = (isVectorizationEnabled ? trueCondNameVectorizationEnabled : falseCondNameVectorizationEnabled); List isVectorizationEnabledCondList = Arrays.asList(isVectorizationEnabledCondName); if (out != null) { out.print(indentString(2)); out.print("enabled: "); out.println(isVectorizationEnabled); out.print(indentString(2)); if (!isVectorizationEnabled) { out.print("enabledConditionsNotMet: "); } else { out.print("enabledConditionsMet: "); } out.println(isVectorizationEnabledCondList); } if (jsonOutput) { json.put("enabled", isVectorizationEnabled); JSONArray jsonArray = new JSONArray(Arrays.asList(isVectorizationEnabledCondName)); if (!isVectorizationEnabled) { json.put("enabledConditionsNotMet", jsonArray); } else { json.put("enabledConditionsMet", jsonArray); } } return new ImmutablePair(isVectorizationEnabled, jsonOutput ? json : null); } public JSONObject getJSONPlan(PrintStream out, ExplainWork work) throws Exception { return getJSONPlan(out, work.getRootTasks(), work.getFetchTask(), work.isFormatted(), work.getExtended(), work.isAppendTaskType(), work.getCboInfo(), work.getOptimizedSQL()); } public JSONObject getJSONPlan(PrintStream out, List> tasks, Task fetchTask, boolean jsonOutput, boolean isExtended, boolean appendTaskType, String cboInfo, String optimizedSQL) throws Exception { // If the user asked for a formatted output, dump the json output // in the output stream JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); if (jsonOutput) { out = null; } if (optimizedSQL != null) { if (jsonOutput) { outJSONObject.put("optimizedSQL", optimizedSQL); } else { out.print("OPTIMIZED SQL: "); out.println(optimizedSQL); } } List ordered = StageIDsRearranger.getExplainOrder(conf, tasks); if (fetchTask != null) { fetchTask.setParentTasks((List)StageIDsRearranger.getFetchSources(tasks)); if (fetchTask.getNumParent() == 0) { fetchTask.setRootTask(true); } ordered.add(fetchTask); } boolean suppressOthersForVectorization = false; if (this.work != null && this.work.isVectorization()) { ImmutablePair planVecPair = outputPlanVectorization(out, jsonOutput); if (this.work.isVectorizationOnly()) { // Suppress the STAGES if vectorization is off. suppressOthersForVectorization = !planVecPair.left; } if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("PLAN VECTORIZATION", planVecPair.right); } } if (!suppressOthersForVectorization) { JSONObject jsonDependencies = outputDependencies(out, jsonOutput, appendTaskType, ordered); if (out != null) { out.println(); } if (jsonOutput) { if (cboInfo != null) { outJSONObject.put("cboInfo", cboInfo); } outJSONObject.put(STAGE_DEPENDENCIES, jsonDependencies); } // Go over all the tasks and dump out the plans JSONObject jsonPlan = outputStagePlans(out, ordered, jsonOutput, isExtended); if (jsonOutput) { outJSONObject.put("STAGE PLANS", jsonPlan); } if (fetchTask != null) { fetchTask.setParentTasks(null); } } return jsonOutput ? outJSONObject : null; } private List toString(Collection objects) { List list = new ArrayList(); for (Object object : objects) { list.add(String.valueOf(object)); } return list; } private Object toJson(String header, String message, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return message; } out.print(header); out.println(": "); out.print(indentString(2)); out.println(message); return null; } private Object toJson(String header, List messages, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return new JSONArray(messages); } out.print(header); out.println(": "); for (String message : messages) { out.print(indentString(2)); out.print(message); out.println(); } return null; } private JSONObject getLocks(PrintStream out, ExplainWork work) { JSONObject jsonObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } List lockComponents = AcidUtils.makeLockComponents(work.getOutputs(), work.getInputs(), conf); if (null != out) { out.print("LOCK INFORMATION:\n"); } List locks = new ArrayList<>(lockComponents.size()); for (LockComponent component : lockComponents) { ExplainLockDesc lockDesc = new ExplainLockDesc(component); if (null != out) { out.print(lockDesc.getFullName()); out.print(" -> "); out.print(lockDesc.getLockType()); out.print('\n'); } else { locks.add(lockDesc); } } if (jsonOutput) { jsonObject.put("LOCK INFORMATION:", locks); } return jsonObject; } @Override public int execute(DriverContext driverContext) { PrintStream out = null; try { Path resFile = work.getResFile(); OutputStream outS = resFile.getFileSystem(conf).create(resFile); out = new PrintStream(outS); if (work.isCbo()) { JSONObject jsonCBOPlan = getJSONCBOPlan(out, work); if (work.isFormatted()) { out.print(jsonCBOPlan); } } else if (work.isLogical()) { JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work); if (work.isFormatted()) { out.print(jsonLogicalPlan); } } else if (work.isAuthorize()) { JSONObject jsonAuth = collectAuthRelatedEntities(out, work); if (work.isFormatted()) { out.print(jsonAuth); } } else if (work.getDependency()) { JSONObject jsonDependencies = getJSONDependencies(work); out.print(jsonDependencies); } else if (work.isLocks()) { JSONObject jsonLocks = getLocks(out, work); if(work.isFormatted()) { out.print(jsonLocks); } } else if (work.isAst()) { // Print out the parse AST if (work.getAstStringTree() != null) { outputAST(work.getAstStringTree(), out, work.isFormatted(), 0); } } else { if (work.isUserLevelExplain()) { // Because of the implementation of the JsonParserFactory, we are sure // that we can get a TezJsonParser. JsonParser jsonParser = JsonParserFactory.getParser(conf); work.getConfig().setFormatted(true); JSONObject jsonPlan = getJSONPlan(out, work); if (work.getCboInfo() != null) { jsonPlan.put("cboInfo", work.getCboInfo()); } try { jsonParser.print(jsonPlan, out); } catch (Exception e) { // if there is anything wrong happen, we bail out. LOG.error("Running explain user level has problem." + " Falling back to normal explain.", e); work.getConfig().setFormatted(false); work.getConfig().setUserLevelExplain(false); jsonPlan = getJSONPlan(out, work); } } else { JSONObject jsonPlan = getJSONPlan(out, work); if (work.isFormatted()) { // use the parser to get the output operators of RS JsonParser jsonParser = JsonParserFactory.getParser(conf); if (jsonParser != null) { jsonParser.print(jsonPlan, null); LOG.info("JsonPlan is augmented to {}", jsonPlan); } out.print(jsonPlan); } } } out.close(); out = null; return (0); } catch (Exception e) { LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e)); setException(e); return (1); } finally { IOUtils.closeStream(out); } } @VisibleForTesting JSONObject collectAuthRelatedEntities(PrintStream out, ExplainWork work) throws Exception { BaseSemanticAnalyzer analyzer = work.getAnalyzer(); HiveOperation operation = queryState.getHiveOperation(); JSONObject object = new JSONObject(new LinkedHashMap<>()); Object jsonInput = toJson("INPUTS", toString(analyzer.getInputs()), out, work); if (work.isFormatted()) { object.put("INPUTS", jsonInput); } Object jsonOutput = toJson("OUTPUTS", toString(analyzer.getOutputs()), out, work); if (work.isFormatted()) { object.put("OUTPUTS", jsonOutput); } String userName = SessionState.get().getAuthenticator().getUserName(); Object jsonUser = toJson("CURRENT_USER", userName, out, work); if (work.isFormatted()) { object.put("CURRENT_USER", jsonUser); } Object jsonOperation = toJson("OPERATION", operation.name(), out, work); if (work.isFormatted()) { object.put("OPERATION", jsonOperation); } if (analyzer.skipAuthorization()) { return object; } final List exceptions = new ArrayList(); Object delegate = SessionState.get().getActiveAuthorizer(); if (delegate != null) { Class itface = SessionState.get().getAuthorizerInterface(); Object authorizer = AuthorizationFactory.create(delegate, itface, new AuthorizationFactory.AuthorizationExceptionHandler() { @Override public void exception(Exception exception) { exceptions.add(exception.getMessage()); } }); SessionState.get().setActiveAuthorizer(authorizer); try { Driver.doAuthorization(queryState.getHiveOperation(), analyzer, ""); } finally { SessionState.get().setActiveAuthorizer(delegate); } } if (!exceptions.isEmpty()) { Object jsonFails = toJson("AUTHORIZATION_FAILURES", exceptions, out, work); if (work.isFormatted()) { object.put("AUTHORIZATION_FAILURES", jsonFails); } } return object; } private static String indentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.append(" "); } return sb.toString(); } @VisibleForTesting JSONObject outputMap(Map mp, boolean hasHeader, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { TreeMap tree = getBasictypeKeyedMap(mp); JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null && hasHeader && !mp.isEmpty()) { out.println(); } for (Entry ent : tree.entrySet()) { // Print the key if (out != null) { out.print(indentString(indent)); out.print(ent.getKey()); out.print(" "); } // Print the value if (isPrintable(ent.getValue())) { if (out != null) { out.print(ent.getValue()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() instanceof List) { if (ent.getValue() != null && !((List)ent.getValue()).isEmpty() && ((List)ent.getValue()).get(0) != null && ((List)ent.getValue()).get(0) instanceof TezWork.Dependency) { if (out != null) { boolean isFirst = true; for (TezWork.Dependency dep: (List)ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getType()); out.print(")"); } out.println(); } if (jsonOutput) { for (TezWork.Dependency dep: (List)ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getType()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else if (ent.getValue() != null && !((List) ent.getValue()).isEmpty() && ((List) ent.getValue()).get(0) != null && ((List) ent.getValue()).get(0) instanceof SparkWork.Dependency) { if (out != null) { boolean isFirst = true; for (SparkWork.Dependency dep: (List) ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getShuffleType()); out.print(", "); out.print(dep.getNumPartitions()); out.print(")"); } out.println(); } if (jsonOutput) { for (SparkWork.Dependency dep: (List) ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getShuffleType()); jsonDep.put("partitions", dep.getNumPartitions()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } } else if (ent.getValue() instanceof Map) { String stringValue = getBasictypeKeyedMap((Map)ent.getValue()).toString(); if (out != null) { out.print(stringValue); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), stringValue); } } else if (ent.getValue() != null) { if (out != null) { out.println(); } JSONObject jsonOut = outputPlan(ent.getValue(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (jsonOutput) { json.put(ent.getKey().toString(), jsonOut); } } else { if (out != null) { out.println(); } } } return jsonOutput ? json : null; } /** * Retruns a map which have either primitive or string keys. * * This is neccessary to discard object level comparators which may sort the objects based on some non-trivial logic. * * @param mp * @return */ private TreeMap getBasictypeKeyedMap(Map mp) { TreeMap ret = new TreeMap(); if (mp.size() > 0) { Object firstKey = mp.keySet().iterator().next(); if (firstKey.getClass().isPrimitive() || firstKey instanceof String) { // keep it as-is ret.putAll(mp); return ret; } else { for (Entry entry : mp.entrySet()) { // discard possibly type related sorting order and replace with alphabetical ret.put(entry.getKey().toString(), entry.getValue()); } } } return ret; } private JSONArray outputList(List l, PrintStream out, boolean hasHeader, boolean extended, boolean jsonOutput, int indent, boolean inTest) throws Exception { boolean first_el = true; boolean nl = false; JSONArray outputArray = new JSONArray(); for (Object o : l) { if (isPrintable(o)) { String delim = first_el ? " " : ", "; if (out != null) { out.print(delim); out.print(o); } if (jsonOutput) { outputArray.put(o); } nl = true; } else { if (first_el && (out != null) && hasHeader) { out.println(); } JSONObject jsonOut = outputPlan(o, out, extended, jsonOutput, jsonOutput ? 0 : (hasHeader ? indent + 2 : indent), "", inTest); if (jsonOutput) { outputArray.put(jsonOut); } } first_el = false; } if (nl && (out != null)) { out.println(); } return jsonOutput ? outputArray : null; } private boolean isPrintable(Object val) { if (val instanceof Boolean || val instanceof String || val instanceof Integer || val instanceof Long || val instanceof Byte || val instanceof Float || val instanceof Double || val instanceof Path) { return true; } if (val != null && val.getClass().isPrimitive()) { return true; } return false; } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, ""); } private boolean isInvokeVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // The EXPLAIN VECTORIZATION option was specified. final boolean desireOnly = this.work.isVectorizationOnly(); final VectorizationDetailLevel desiredVecDetailLevel = this.work.isVectorizationDetailLevel(); switch (vectorization) { case NON_VECTORIZED: // Display all non-vectorized leaf objects unless ONLY. if (desireOnly) { invokeFlag = false; } break; case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: if (vectorization.rank < desiredVecDetailLevel.rank) { // This detail not desired. invokeFlag = false; } break; case SUMMARY_PATH: case OPERATOR_PATH: if (desireOnly) { if (vectorization.rank < desiredVecDetailLevel.rank) { // Suppress headers and all objects below. invokeFlag = false; } } break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } private boolean isInvokeNonVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // Do not display vectorization objects. switch (vectorization) { case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: invokeFlag = false; break; case NON_VECTORIZED: // No action. break; case SUMMARY_PATH: case OPERATOR_PATH: // Always include headers since they contain non-vectorized objects, too. break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } @VisibleForTesting JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, appendToHeader, queryState.getConf().getBoolVar(ConfVars.HIVE_IN_TEST)); } public JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader, boolean inTest) throws Exception { // Check if work has an explain annotation Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class); String keyJSONObject = null; if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } if (invokeFlag) { keyJSONObject = xpl_note.displayName(); if (out != null) { out.print(indentString(indent)); if (appendToHeader != null && !appendToHeader.isEmpty()) { out.println(xpl_note.displayName() + appendToHeader); } else { out.println(xpl_note.displayName()); } } } } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; // If this is an operator then we need to call the plan generation on the // conf and then the children if (work instanceof Operator) { Operator operator = (Operator) work; if (operator.getConf() != null) { String appender = isLogical ? " (" + operator.getOperatorId() + ")" : ""; JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput, jsonOutput ? 0 : indent, appender, inTest); if (this.work != null && (this.work.isUserLevelExplain() || this.work.isFormatted())) { if (jsonOut != null && jsonOut.length() > 0) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:", operator.getOperatorId()); } if (!this.work.isUserLevelExplain() && this.work.isFormatted() && operator.getConf() instanceof ReduceSinkDesc ) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("outputname:", ((ReduceSinkDesc) operator.getConf()).getOutputName()); } } if (jsonOutput) { json = jsonOut; } } if (!visitedOps.contains(operator) || !isLogical) { visitedOps.add(operator); if (operator.getChildOperators() != null) { int cindent = jsonOutput ? 0 : indent + 2; for (Operator op : operator.getChildOperators()) { JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent, "", inTest); if (jsonOutput) { ((JSONObject)json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut); } } } } if (jsonOutput) { return json; } return null; } // We look at all methods that generate values for explain Method[] methods = work.getClass().getMethods(); Arrays.sort(methods, new MethodComparator()); for (Method m : methods) { int prop_indents = jsonOutput ? 0 : indent + 2; note = AnnotationUtils.getAnnotation(m, Explain.class); if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (invokeFlag) { if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } } if (invokeFlag) { Object val = null; try { if(postProcess(xpl_note)) { val = m.invoke(work, inTest); } else{ val = m.invoke(work); } } catch (InvocationTargetException ex) { // Ignore the exception, this may be caused by external jars val = null; } if (val == null) { continue; } if(xpl_note.jsonOnly() && !jsonOutput) { continue; } String header = null; boolean skipHeader = xpl_note.skipHeader(); boolean emptyHeader = false; if (!xpl_note.displayName().equals("")) { header = indentString(prop_indents) + xpl_note.displayName() + ":"; } else { emptyHeader = true; prop_indents = indent; header = indentString(prop_indents); } // Try the output as a primitive object if (isPrintable(val)) { if (out != null && shouldPrint(xpl_note, val)) { if (!skipHeader) { out.print(header); out.print(" "); } out.println(val); } if (jsonOutput && shouldPrint(xpl_note, val)) { json.put(header, val.toString()); } continue; } int ind = 0; if (!jsonOutput) { if (!skipHeader) { ind = prop_indents + 2; } else { ind = indent; } } // Try this as a map if (val instanceof Map) { // Go through the map and print out the stuff Map mp = (Map) val; if (out != null && !skipHeader && mp != null && !mp.isEmpty()) { out.print(header); } JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput, ind); if (jsonOutput && !mp.isEmpty()) { json.put(header, jsonOut); } continue; } // Try this as a list if (val instanceof List || val instanceof Set) { List l = val instanceof List ? (List)val : new ArrayList((Set)val); if (out != null && !skipHeader && l != null && !l.isEmpty()) { out.print(header); } JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput, ind, inTest); if (jsonOutput && !l.isEmpty()) { json.put(header, jsonOut); } continue; } // Finally check if it is serializable try { if (!skipHeader && out != null) { out.println(header); } JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind, "", inTest); if (jsonOutput && jsonOut != null && jsonOut.length() != 0) { if (!skipHeader) { json.put(header, jsonOut); } else { for(String k: JSONObject.getNames(jsonOut)) { json.put(k, jsonOut.get(k)); } } } continue; } catch (ClassCastException ce) { // Ignore } } } } if (jsonOutput) { if (keyJSONObject != null) { JSONObject ret = new JSONObject(new LinkedHashMap<>()); ret.put(keyJSONObject, json); return ret; } return json; } return null; } /** * use case: this is only use for testing purposes. For instance, we might * want to sort the expressions in a filter so we get deterministic comparable * golden files */ private boolean postProcess(Explain exp) { return exp.postProcess(); } /** * use case: we want to print the object in explain only if it is true * how to do : print it unless the following 3 are all true: * 1. displayOnlyOnTrue tag is on * 2. object is boolean * 3. object is false * @param exp * @param val * @return */ private boolean shouldPrint(Explain exp, Object val) { if (exp.displayOnlyOnTrue() && (val instanceof Boolean) & !((Boolean)val)) { return false; } return true; } private JSONObject outputPlan(Task task, PrintStream out, JSONObject parentJSON, boolean extended, boolean jsonOutput, int indent) throws Exception { if (out != null) { out.print(indentString(indent)); out.print("Stage: "); out.print(task.getId()); out.print("\n"); } // Start by getting the work part of the task and call the output plan for // the work JSONObject jsonOutputPlan = outputPlan(task.getWork(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (out != null) { out.println(); } if (jsonOutput) { parentJSON.put(task.getId(), jsonOutputPlan); } return null; } @VisibleForTesting JSONObject outputDependencies(Task task, PrintStream out, JSONObject parentJson, boolean jsonOutput, boolean taskType, int indent) throws Exception { boolean first = true; JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null) { out.print(indentString(indent)); out.print(task.getId()); } if ((task.getParentTasks() == null || task.getParentTasks().isEmpty())) { if (task.isRootTask()) { if (out != null) { out.print(" is a root stage"); } if (jsonOutput) { json.put("ROOT STAGE", "TRUE"); } } } else { StringBuilder s = new StringBuilder(); first = true; for (Task parent : task.getParentTasks()) { if (!first) { s.append(", "); } first = false; s.append(parent.getId()); } if (out != null) { out.print(" depends on stages: "); out.print(s.toString()); } if (jsonOutput) { json.put("DEPENDENT STAGES", s.toString()); } } Task currBackupTask = task.getBackupTask(); if (currBackupTask != null) { if (out != null) { out.print(" has a backup stage: "); out.print(currBackupTask.getId()); } if (jsonOutput) { json.put("BACKUP STAGE", currBackupTask.getId()); } } if (task instanceof ConditionalTask && ((ConditionalTask) task).getListTasks() != null) { StringBuilder s = new StringBuilder(); first = true; for (Task con : ((ConditionalTask) task).getListTasks()) { if (!first) { s.append(", "); } first = false; s.append(con.getId()); } if (out != null) { out.print(" , consists of "); out.print(s.toString()); } if (jsonOutput) { json.put("CONDITIONAL CHILD TASKS", s.toString()); } } if (taskType) { if (out != null) { out.print(" ["); out.print(task.getType()); out.print("]"); } if (jsonOutput) { json.put("TASK TYPE", task.getType().name()); } } if (out != null) { out.println(); } return jsonOutput ? json : null; } public String outputAST(String treeString, PrintStream out, boolean jsonOutput, int indent) throws JSONException { if (out != null) { out.print(indentString(indent)); out.println("ABSTRACT SYNTAX TREE:"); out.print(indentString(indent + 2)); out.println(treeString); } return jsonOutput ? treeString : null; } public JSONObject outputDependencies(PrintStream out, boolean jsonOutput, boolean appendTaskType, List tasks) throws Exception { if (out != null) { out.println(STAGE_DEPENDENCIES + ":"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { JSONObject jsonOut = outputDependencies(task, out, json, jsonOutput, appendTaskType, 2); if (jsonOutput && jsonOut != null) { json.put(task.getId(), jsonOut); } } return jsonOutput ? json : null; } public JSONObject outputStagePlans(PrintStream out, List tasks, boolean jsonOutput, boolean isExtended) throws Exception { if (out != null) { out.println("STAGE PLANS:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { outputPlan(task, out, json, isExtended, jsonOutput, 2); } return jsonOutput ? json : null; } /** * MethodComparator. * */ public class MethodComparator implements Comparator { @Override public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } } @Override public StageType getType() { return StageType.EXPLAIN; } @Override public String getName() { return "EXPLAIN"; } public static List getResultSchema() { FieldSchema tmpFieldSchema = new FieldSchema(); List colList = new ArrayList(); tmpFieldSchema.setName(EXPL_COLUMN_NAME); tmpFieldSchema.setType(STRING_TYPE_NAME); colList.add(tmpFieldSchema); return colList; } @Override public boolean canExecuteInParallel() { return false; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14844 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/ExplainTask.java/#L84-L1302 | 1 | 2563 | 14844 | major |
| 2216 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 13536 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 2216 | 13536 | major |
| 2043 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12862 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 | 1 | 2043 | 12862 | minor |
| 4768 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12832 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 2 | 4768 | 12832 | minor |
| 3476 | {"response":"YES I found bad smells","bad smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractClientProvider { public AbstractClientProvider() { } /** * Generates a fixed format of application tags given one or more of * application name, version and description. This allows subsequent query for * an application with a name only, version only or description only or any * combination of those as filters. * * @param appName name of the application * @param appVersion version of the application * @param appDescription brief description of the application * @return */ public static final Set createApplicationTags(String appName, String appVersion, String appDescription) { Set tags = new HashSet<>(); tags.add(ServiceUtils.createNameTag(appName)); if (appVersion != null) { tags.add(ServiceUtils.createVersionTag(appVersion)); } if (appDescription != null) { tags.add(ServiceUtils.createDescriptionTag(appDescription)); } return tags; } /** * Validate the artifact. * @param artifact */ public abstract void validateArtifact(Artifact artifact, String compName, FileSystem fileSystem) throws IOException; protected abstract void validateConfigFile(ConfigFile configFile, String compName, FileSystem fileSystem) throws IOException; /** * Validate the config files. * @param configFiles config file list * @param fs file system */ public void validateConfigFiles(List configFiles, String compName, FileSystem fs) throws IOException { Set destFileSet = new HashSet<>(); for (ConfigFile file : configFiles) { if (file.getType() == null) { throw new IllegalArgumentException("File type is empty"); } ConfigFile.TypeEnum fileType = file.getType(); if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) { if (StringUtils.isEmpty(file.getSrcFile()) && !file.getProperties().containsKey(CONTENT)) { throw new IllegalArgumentException(MessageFormat.format("For {0} " + "format, either src_file must be specified in ConfigFile," + " or the \"{1}\" key must be specified in " + "the 'properties' field of ConfigFile. ", ConfigFile.TypeEnum.TEMPLATE, CONTENT)); } } else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals( ConfigFile.TypeEnum.ARCHIVE)) { if (!file.getProperties().isEmpty()) { throw new IllegalArgumentException(String .format("For %s format, should not specify any 'properties.'", fileType)); } String srcFile = file.getSrcFile(); if (srcFile == null || srcFile.isEmpty()) { throw new IllegalArgumentException(String.format( "For %s format, should make sure that srcFile is specified", fileType)); } FileStatus fileStatus = fs.getFileStatus(new Path(srcFile)); if (fileStatus != null && fileStatus.isDirectory()) { throw new IllegalArgumentException("srcFile=" + srcFile + " is a directory, which is not supported."); } } if (!StringUtils.isEmpty(file.getSrcFile())) { Path p = new Path(file.getSrcFile()); if (!fs.exists(p)) { throw new IllegalArgumentException( "Specified src_file does not exist on " + fs.getScheme() + ": " + file.getSrcFile()); } } if (StringUtils.isEmpty(file.getDestFile())) { throw new IllegalArgumentException("dest_file is empty."); } if (destFileSet.contains(file.getDestFile())) { throw new IllegalArgumentException( "Duplicated ConfigFile exists: " + file.getDestFile()); } destFileSet.add(file.getDestFile()); java.nio.file.Path destPath = Paths.get(file.getDestFile()); if (!destPath.isAbsolute() && destPath.getNameCount() > 1) { throw new IllegalArgumentException("Non-absolute dest_file has more " + "than one path element"); } // provider-specific validation validateConfigFile(file, compName, fs); } } } |
blob | long method | t | t | f | long method | blob | 0 | 7072 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/AbstractClientProvider.java/#L38-L150 | 1 | 3476 | 7072 | major |
| 547 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 5553 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 2 | 547 | 5553 | critical |
| 1429 | {"status":"OK"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Not specified | f | f | f | false | 0 | 10951 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 1429 | 10951 | major | |
| 2323 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 14132 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 1 | 2323 | 14132 | minor |
| 2109 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Not specified | f | f | f | false | 0 | 13180 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 2109 | 13180 | minor | |
| 2584 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14973 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2584 | 14973 | major |
| 211 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Primitive obsession 5. Inappropriate intimacy 6. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | Feature envy2 Long method3 Duplicate code4 Primitive obsession5 Inappropriate intimacy6 Shotgun surgery | t | f | f | . Feature envy2. Long method3. Duplicate code4. Primitive obsession5. Inappropriate intimacy6. Shotgun surgery | data class | 0 | 2314 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 211 | 2314 | major |
| 1668 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class DirectExecutorService implements ExecutorService { static final DirectExecutorService INSTANCE = new DirectExecutorService(); private boolean isShutdown = false; @Override public void shutdown() { isShutdown = true; } @Override @Nonnull public List shutdownNow() { isShutdown = true; return Collections.emptyList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isShutdown; } @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) { return isShutdown; } @Override @Nonnull public Future submit(@Nonnull Callable task) { try { T result = task.call(); return new CompletedFuture<>(result, null); } catch (Exception e) { return new CompletedFuture<>(null, e); } } @Override @Nonnull public Future submit(@Nonnull Runnable task, T result) { task.run(); return new CompletedFuture<>(result, null); } @Override @Nonnull public Future submit(@Nonnull Runnable task) { task.run(); return new CompletedFuture<>(null, null); } @Override @Nonnull public List> invokeAll(@Nonnull Collection> tasks) { ArrayList> result = new ArrayList<>(); for (Callable task : tasks) { try { result.add(new CompletedFuture<>(task.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } return result; } @Override @Nonnull public List> invokeAll( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); Iterator> iterator = tasks.iterator(); ArrayList> result = new ArrayList<>(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { result.add(new CompletedFuture<>(callable.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } while (iterator.hasNext()) { iterator.next(); result.add(new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean isDone() { return false; } @Override public T get() { throw new CancellationException("Task has been cancelled."); } @Override public T get(long timeout, @Nonnull TimeUnit unit) { throw new CancellationException("Task has been cancelled."); } }); } return result; } @Override @Nonnull public T invokeAny(@Nonnull Collection> tasks) throws ExecutionException { Exception exception = null; for (Callable task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); } @Override public T invokeAny( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis(timeout); Exception exception = null; Iterator> iterator = tasks.iterator(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { return callable.call(); } catch (Exception e) { // ignore exception and try next exception = e; } } if (iterator.hasNext()) { throw new TimeoutException("Could not finish execution of tasks within time."); } else { throw new ExecutionException("No tasks finished successfully.", exception); } } @Override public void execute(@Nonnull Runnable command) { command.run(); } static class CompletedFuture implements Future { private final V value; private final Exception exception; CompletedFuture(V value, Exception exception) { this.value = value; this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public V get() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } else { return value; } } @Override public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException { return get(); } } } |
blob | Long Method, Feature Envy | t | f | f | Long Method, Feature Envy | blob | 0 | 11626 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/DirectExecutorService.java/#L37-L252 | 1 | 1668 | 11626 | minor |
| 354 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: elements of the Feedback class are being accessed by multiple methods 3. Magic numbers- for example, in the version() method where the version format is hardcoded as "1.0.0" 4. Duplicate code- for example, the skipWhitespaces() method is being used multiple times with the same code. 5. Violation of Single Responsibility Principle (SRP)- the HeaderParser class is responsible for parsing, validating, and reporting any errors. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } } |
blob | Long method2 Feature envy: elements of the Feedback class are being accessed by multiple methods3 Magic numbers- for example, in the version() method where the version format is hardcoded as " | t | f | f | . Long method2. Feature envy: elements of the Feedback class are being accessed by multiple methods3. Magic numbers- for example, in the version() method where the version format is hardcoded as " | blob | 0 | 3651 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 | 2 | 354 | 3651 | major |
| 1308 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10677 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 2 | 1308 | 10677 | minor |
| 1396 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | long method | t | t | f | long method | blob | 0 | 10852 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 1 | 1396 | 10852 | minor |
| 5128 | {"message": "YES I found bad smells", "bad smells are": ["3. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | 3. long method | t | t | f | 3. long method | blob | 0 | 14367 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 1 | 5128 | 14367 | minor |
| 2206 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 13513 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 2 | 2206 | 13513 | major |
| 1419 | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | f | f | f | long method | 0 | 10925 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1419 | 10925 | minor | |||
| 303 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3173 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 1 | 303 | 3173 | major |
| 1317 | YES I found bad smells the bad smells are: 1. Commented out code 2. Complex conditional statements 3. Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4. Magic numbers 5. Inconsistent formatting and spacing 6. Inefficient use of whitespace 7. Potential Null Pointer Exception 8. Confusing variable names (e.g. nameSeg, arraySeg) 9. Duplicate code in the if-else statement 10. Non-descriptive and vague method name 11. Nested conditional statements 12. Potential error-prone code (e.g. using a logger to throw an exception) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Commented out code 2 Complex conditional statements 3 Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4 Magic numbers 5 Inconsistent formatting and spacing 6 Inefficient use of whitespace 7 Potential Null Pointer Exception 8 Confusing variable names (eg nameSeg, arraySeg) 9 Duplicate code in the if-else statement | t | f | f | . Commented out code 2. Complex conditional statements 3. Violation of Single Responsibility Principle (SRP) - the method is responsible for both parsing and adding to a projection 4. Magic numbers 5. Inconsistent formatting and spacing 6. Inefficient use of whitespace 7. Potential Null Pointer Exception 8. Confusing variable names (e.g. nameSeg, arraySeg) 9. Duplicate code in the if-else statement | long method | 0 | 10691 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1317 | 10691 | minor |
| 124 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface PropertyPathPart extends EObject { /** * Returns the value of the 'Name' attribute. * * * If the meaning of the 'Name' attribute isn't clear, * there really should be more of a description here... * * * @return the value of the 'Name' attribute. * @see #setName(String) * @see org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.Bug332217TestLanguagePackage#getPropertyPathPart_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.PropertyPathPart#getName Name}' attribute. * * * @param value the new value of the 'Name' attribute. * @see #getName() * @generated */ void setName(String value); } // PropertyPathPart |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1552 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug332217TestLanguage/PropertyPathPart.java/#L24-L52 | 2 | 124 | 1552 | critical |
| 2064 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12979 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 2 | 2064 | 12979 | minor |
| 2611 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15040 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 2611 | 15040 | minor |
| 531 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 5477 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 2 | 531 | 5477 | minor |
| 591 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { MessageDispatchNotification info = (MessageDispatchNotification)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalLong1(wireFormat, info.getDeliverySequenceId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); return rc + 0; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 5901 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationMarshaller.java/#L77-L88 | 1 | 591 | 5901 | minor |
| 898 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 8150 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 | 1 | 898 | 8150 | minor |
| 24 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 691 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 24 | 691 | critical |
| 434 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | long method | t | t | f | long method | blob | 0 | 4283 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 1 | 434 | 4283 | major |
| 2039 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12844 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2039 | 12844 | minor |
| 731 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6879 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 731 | 6879 | minor |
| 1662 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11614 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1662 | 11614 | minor |
| 2479 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14592 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 2479 | 14592 | major |
| 252 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2712 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 1 | 252 | 2712 | minor |
| 455 | the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | Long method2 Feature envy | f | f | f | . Long method2. Feature envy | blob | 0 | 4445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 2 | 455 | 4445 | minor |
| 1274 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 10582 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 1 | 1274 | 10582 | major |
| 741 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6975 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 741 | 6975 | minor |
| 1130 | Yes, bad smells I found are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10018 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1130 | 10018 | minor |
| 1895 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class SwiftUtils { public static final String READ = "read(buffer, offset, length)"; /** * Join two (non null) paths, inserting a forward slash between them * if needed * * @param path1 first path * @param path2 second path * @return the combined path */ public static String joinPaths(String path1, String path2) { StringBuilder result = new StringBuilder(path1.length() + path2.length() + 1); result.append(path1); boolean insertSlash = true; if (path1.endsWith("/")) { insertSlash = false; } else if (path2.startsWith("/")) { insertSlash = false; } if (insertSlash) { result.append("/"); } result.append(path2); return result.toString(); } /** * This test contains the is-directory logic for Swift, so if * changed there is only one place for it. * * @param fileStatus status to examine * @return true if we consider this status to be representative of a * directory. */ public static boolean isDirectory(FileStatus fileStatus) { return fileStatus.isDirectory() || isFilePretendingToBeDirectory(fileStatus); } /** * Test for the entry being a file that is treated as if it is a * directory * * @param fileStatus status * @return true if it meets the rules for being a directory */ public static boolean isFilePretendingToBeDirectory(FileStatus fileStatus) { return fileStatus.getLen() == 0; } /** * Predicate: Is a swift object referring to the root directory? * @param swiftObject object to probe * @return true iff the object refers to the root */ public static boolean isRootDir(SwiftObjectPath swiftObject) { return swiftObject.objectMatches("") || swiftObject.objectMatches("/"); } /** * Sprintf() to the log iff the log is at debug level. If the log * is not at debug level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void debug(Logger log, String text, Object... args) { if (log.isDebugEnabled()) { log.debug(String.format(text, args)); } } /** * Log an exception (in text and trace) iff the log is at debug * @param log Log to use * @param text text message * @param ex exception */ public static void debugEx(Logger log, String text, Exception ex) { if (log.isDebugEnabled()) { log.debug(text + ex, ex); } } /** * Sprintf() to the log iff the log is at trace level. If the log * is not at trace level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void trace(Logger log, String text, Object... args) { if (log.isTraceEnabled()) { log.trace(String.format(text, args)); } } /** * Given a partition number, calculate the partition value. * This is used in the SwiftNativeOutputStream, and is placed * here for tests to be able to calculate the filename of * a partition. * @param partNumber part number * @return a string to use as the filename */ public static String partitionFilenameFromNumber(int partNumber) { return String.format("%06d", partNumber); } /** * List a a path to string * @param fileSystem filesystem * @param path directory * @return a listing of the filestatuses of elements in the directory, one * to a line, preceded by the full path of the directory * @throws IOException connectivity problems */ public static String ls(FileSystem fileSystem, Path path) throws IOException { if (path == null) { //surfaces when someone calls getParent() on something at the top of the path return "/"; } FileStatus[] stats; String pathtext = "ls " + path; try { stats = fileSystem.listStatus(path); } catch (FileNotFoundException e) { return pathtext + " -file not found"; } catch (IOException e) { return pathtext + " -failed: " + e; } return pathtext + fileStatsToString(stats, "\n"); } /** * Take an array of filestatus and convert to a string (prefixed w/ a [01] counter * @param stats array of stats * @param separator separator after every entry * @return a stringified set */ public static String fileStatsToString(FileStatus[] stats, String separator) { StringBuilder buf = new StringBuilder(stats.length * 128); for (int i = 0; i < stats.length; i++) { buf.append(String.format("[%02d] %s", i, stats[i])).append(separator); } return buf.toString(); } /** * Verify that the basic args to a read operation are valid; * throws an exception if not -with meaningful text including * @param buffer destination buffer * @param off offset * @param len number of bytes to read * @throws NullPointerException null buffer * @throws IndexOutOfBoundsException on any invalid range. */ public static void validateReadArgs(byte[] buffer, int off, int len) { if (buffer == null) { throw new NullPointerException("Null byte array in"+ READ); } if (off < 0 ) { throw new IndexOutOfBoundsException("Negative buffer offset " + off + " in " + READ); } if (len < 0 ) { throw new IndexOutOfBoundsException("Negative read length " + len + " in " + READ); } if (off > buffer.length) { throw new IndexOutOfBoundsException("Buffer offset of " + off + "beyond buffer size of " + buffer.length + " in " + READ); } } } |
blob | long method | t | t | f | long method | blob | 0 | 12333 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-openstack/src/main/java/org/apache/hadoop/fs/swift/util/SwiftUtils.java/#L32-L216 | 1 | 1895 | 12333 | minor |
| 1408 | {"message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10885 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 2 | 1408 | 10885 | minor |
| 1226 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10352 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 1226 | 10352 | minor |
| 163 | {"message":"YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorTestCaseFinder { private static final Logger log = LoggerFactory.getLogger(IteratorTestCaseFinder.class); /** * Instantiates all test cases provided. * * @return A list of {@link IteratorTestCase}s. */ public static List findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet classes = cp .getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List testCases = new ArrayList<>(); // final Set> classes = // reflections.getSubTypesOf(IteratorTestCase.class); for (ClassInfo classInfo : classes) { Class clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; } } |
blob | Not specified | f | f | f | false | 0 | 1997 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/iterator-test-harness/src/main/java/org/apache/accumulo/iteratortest/IteratorTestCaseFinder.java/#L35-L81 | 2 | 163 | 1997 | minor | |
| 210 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 1 | 210 | 2313 | major |
| 1834 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | t | f | f | long method | 0 | 12132 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 1834 | 12132 | minor | ||
| 2047 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 12877 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 2047 | 12877 | major |
| 509 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 5182 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 | 2 | 509 | 5182 | major |
| 1863 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | long method | t | t | f | long method | blob | 0 | 12226 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 1 | 1863 | 12226 | minor |
| 1911 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicated code 3. Feature envy 4. Poor naming convention 5. Inconsistent naming 6. Incomplete comment and method descriptions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
blob | Long method 2 Duplicated code3 Feature envy4 Poor naming convention 5 Inconsistent naming 6 Incomplete comment and method descriptions | t | f | f | . Long method 2. Duplicated code3. Feature envy4. Poor naming convention 5. Inconsistent naming 6. Incomplete comment and method descriptions | blob | 0 | 12400 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 1911 | 12400 | minor |
| 1674 | YES I found bad smells The bad smells are: 1. Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes. 2. Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods. 3. Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null. 4. Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case. 5. Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes2 Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods3 Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null4 Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case5 Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed | t | f | f | . Feature envy: The Mina2Configuration class contains a lot of getters and setters for the various options, which shows that functionality is probably spread out among different classes.2. Long method: The Mina2Configuration class has 78 lines of code with various options and logic, indicating that the method may be doing too many things and could be broken up into smaller, more focused methods.3. Dead code: The getCharsetName() method contains an if statement which can never be true, as the encoding parameter can never be null.4. Non-standard naming convention: The setSslContextParameters() method uses camel case instead of the standard Java naming convention of using lower camel case.5. Commented-out code: The getUriString() method contains code that is commented out, which may indicate that it is no longer needed but was not removed. | data class | 0 | 11643 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 2 | 1674 | 11643 | critical |
| 1663 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Indirect coupling 4. Code duplication 5. Magic numbers 6. Dense code 7. Hardcoded values 8. Lack of comments/documentation 9. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
blob | Long method 2 Feature envy 3 Indirect coupling 4 Code duplication 5 Magic numbers6 Dense code7 Hardcoded values8 Lack of comments/documentation 9 Inconsistent naming conventions | t | f | f | . Long method 2. Feature envy 3. Indirect coupling 4. Code duplication 5. Magic numbers6. Dense code7. Hardcoded values8. Lack of comments/documentation 9. Inconsistent naming conventions | blob | 0 | 11615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1663 | 11615 | minor |
| 730 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RealRowResultSetStatistics extends RealNoPutResultSetStatistics { /* Leave these fields public for object inspectors */ public int rowsReturned; // CONSTRUCTORS /** * * */ public RealRowResultSetStatistics( int numOpens, int rowsSeen, int rowsFiltered, long constructorTime, long openTime, long nextTime, long closeTime, int resultSetNumber, int rowsReturned, double optimizerEstimatedRowCount, double optimizerEstimatedCost ) { super( numOpens, rowsSeen, rowsFiltered, constructorTime, openTime, nextTime, closeTime, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost ); this.rowsReturned = rowsReturned; } // ResultSetStatistics methods /** * Return the statement execution plan as a String. * * @param depth Indentation level. * * @return String The statement execution plan as a String. */ public String getStatementExecutionPlanText(int depth) { initFormatInfo(depth); return indent + MessageService.getTextMessage(SQLState.RTS_ROW_RS) + ":\n" + indent + MessageService.getTextMessage(SQLState.RTS_NUM_OPENS) + " = " + numOpens + "\n" + indent + MessageService.getTextMessage( SQLState.RTS_ROWS_RETURNED) + " = " + rowsReturned + "\n" + dumpTimeStats(indent, subIndent) + "\n" + dumpEstimatedCosts(subIndent) + "\n"; } /** * Return information on the scan nodes from the statement execution * plan as a String. * * @param depth Indentation level. * @param tableName if not NULL then print information for this table only * * @return String The information on the scan nodes from the * statement execution plan as a String. */ public String getScanStatisticsText(String tableName, int depth) { return ""; } // Class implementation public String toString() { return getStatementExecutionPlanText(0); } /** * Format for display, a name for this node. * */ public String getNodeName(){ return MessageService.getTextMessage(SQLState.RTS_ROW_RS); } // ----------------------------------------------------- // XPLAINable Implementation // ----------------------------------------------------- public void accept(XPLAINVisitor visitor) { // I have no children, inform my visitor about that visitor.setNumberOfChildren(0); // pre-order, depth-first traversal // me first visitor.visit(this); // I'm a leaf node, I have no children ... } public String getRSXplainType() { return XPLAINUtil.OP_ROW; } public Object getResultSetDescriptor(Object rsID, Object parentID, Object scanID, Object sortID, Object stmtID, Object timingID) { return new XPLAINResultSetDescriptor( (UUID)rsID, getRSXplainType(), getRSXplainDetails(), this.numOpens, null, // the number of index updates null, // lock mode null, // lock granularity (UUID)parentID, this.optimizerEstimatedRowCount, this.optimizerEstimatedCost, null, // the affected rows null, // the deferred rows null, // the input rows this.rowsSeen, null, // the seen rows right this.rowsFiltered, this.rowsReturned, null, // the empty right rows null, // index key optimization (UUID)scanID, (UUID)sortID, (UUID)stmtID, (UUID)timingID); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6866 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/rts/RealRowResultSetStatistics.java/#L46-L187 | 2 | 730 | 6866 | minor |
| 2184 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13426 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 2 | 2184 | 13426 | minor |
| 1990 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12680 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 | 1 | 1990 | 12680 | major |
| 1114 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9896 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 1114 | 9896 | minor |
| 1700 | {"response":"YES I found bad smells","the bad smells are":["1.Long method","2.Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
blob | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | blob | 0 | 11735 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 1700 | 11735 | major |
| 2705 | YES, I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Lack of encapsulation 5. Switch statements 6. Inconsistent naming conventions 7. Unnecessary comments 8. Magic numbers 9. Use of null values | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | Feature envy2 Long method3 Duplicate code4 Lack of encapsulation5 Switch statements6 Inconsistent naming conventions7 Unnecessary comments8 Magic numbers9 Use of null values | t | f | f | . Feature envy2. Long method3. Duplicate code4. Lack of encapsulation5. Switch statements6. Inconsistent naming conventions7. Unnecessary comments8. Magic numbers9. Use of null values | blob | 0 | 15343 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 2 | 2705 | 15343 | minor |
| 848 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 7846 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 848 | 7846 | major |
| 573 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (methods have repeated logic instead of using variables from the class) 3. Data and code duplication (methods are repeated for toString, equals, hashCode) 4. Class is not using encapsulation (variables are marked as final, but getters and setters are not used) 5. Unnecessary constructor (not used for anything) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy (methods have repeated logic instead of using variables from the class)3 Data and code duplication (methods are repeated for toString, equals, hashCode)4 Class is not using encapsulation (variables are marked as final, but getters and setters are not used)5 Unnecessary constructor (not used for anything) | t | f | f | . Long method2. Feature envy (methods have repeated logic instead of using variables from the class)3. Data and code duplication (methods are repeated for toString, equals, hashCode)4. Class is not using encapsulation (variables are marked as final, but getters and setters are not used)5. Unnecessary constructor (not used for anything) | data class | 0 | 5757 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 573 | 5757 | critical |
| 3413 | {"response": "YES I found bad smells", "Detected bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @Metrics(context="metricssystem") public class MetricsSystemImpl extends MetricsSystem implements MetricsSource { static final Log LOG = LogFactory.getLog(MetricsSystemImpl.class); static final String MS_NAME = "MetricsSystem"; static final String MS_STATS_NAME = MS_NAME +",sub=Stats"; static final String MS_STATS_DESC = "Metrics system metrics"; static final String MS_CONTROL_NAME = MS_NAME +",sub=Control"; static final String MS_INIT_MODE_KEY = "hadoop.metrics.init.mode"; enum InitMode { NORMAL, STANDBY } private final Map sources; private final Map allSources; private final Map sinks; private final Map allSinks; private final List callbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private int period; // seconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.info(this.prefix +" metrics system started (again)"); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.info(prefix +" metrics system started in standby mode"); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.info(prefix +" metrics system started"); for (Callback cb : callbacks) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.info(prefix +" metrics system stopped (again)"); return; } for (Callback cb : callbacks) cb.preStop(); LOG.info("Stopping "+ prefix +" metrics system..."); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.info(prefix +" metrics system stopped."); for (Callback cb : callbacks) cb.postStop(); } @Override public synchronized T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { LOG.warn("Sink "+ name +" already exists!"); return sink; } allSinks.put(name, sink); if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); sa.start(); LOG.info("Registered sink "+ name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance( callback.getClass().getClassLoader(), new Class[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback "+ method.getName(), e); } return null; } })); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.save(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period * 1000; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn(e); } } }, millis, millis); LOG.info("Scheduled snapshot period at "+ period +" second(s)."); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.now(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.now() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.now(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.now() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); int confPeriod = 0; for (Entry entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); confPeriod = confPeriod == 0 ? sinkPeriod : ArithmeticUtils.gcd(confPeriod, sinkPeriod); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } period = confPeriod > 0 ? confPeriod : config.getInt(PERIOD_KEY, PERIOD_DEFAULT); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT), conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.info(prefix +" metrics system shutdown complete."); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf((m2 == null ? InitMode.NORMAL.name() : m2) .toUpperCase(Locale.US)); } } |
blob | data class | t | t | f | data class | blob | 0 | 6664 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java/#L69-L601 | 1 | 3413 | 6664 | major |
| 2205 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13511 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 2205 | 13511 | minor |
| 1912 | { YES I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 12401 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 2 | 1912 | 12401 | major |
| 4481 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 11863 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 2 | 4481 | 11863 | critical |
| 2333 | YES, I found bad smells the bad smells are: 1. Long method 2. Large class 3. Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc.) instead of being self-contained. 4. Duplication: getConfig() and getConfig().getInt() are repeated multiple times in the code. 5. Magic numbers: Default values and ports are hard coded instead of being declared as constants. 6. Inconsistent naming conventions: the use of both snake_case and camelCase in variable names. 7. Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class. 8. Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp. 9. Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions. 10. Method chaining: The method WebApps.$for() is used for creating the webApp variable in a single line, making it difficult to understand what is happening. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method2 Large class3 Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc) instead of being self-contained4 Duplication: getConfig() and getConfig()getInt() are repeated multiple times in the code5 Magic numbers: Default values and ports are hard coded instead of being declared as constants6 Inconsistent naming conventions: the use of both snake_case and camelCase in variable names 7 Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class8 Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp9 Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions | t | f | f | . Long method2. Large class3. Feature envy: HistoryClientService is accessing and manipulating data from other classes (HistoryContext, JHSDelegationTokenSecretManager, etc.) instead of being self-contained.4. Duplication: getConfig() and getConfig().getInt() are repeated multiple times in the code.5. Magic numbers: Default values and ports are hard coded instead of being declared as constants.6. Inconsistent naming conventions: the use of both snake_case and camelCase in variable names. 7. Use of nested classes: The class HSClientProtocolHandler is declared within the HistoryClientService class instead of being a separate top-level class.8. Single responsibility principle violation: The HistoryClientService class is responsible for both handling requests from clients and managing the server and webApp.9. Incomplete error handling: Some methods, such as killJob(), do not handle errors properly and just throw IOExceptions. | data class | 0 | 14159 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2333 | 14159 | minor |
| 823 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 7702 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 2 | 823 | 7702 | minor |
| 247 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2657 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 1 | 247 | 2657 | minor |
| 1532 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 11209 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 1532 | 11209 | major |
| 2341 | YES I found bad smells The bad smells are: 1. Mutable state 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | Mutable state2 Long method 3 Feature envy | t | f | f | . Mutable state2. Long method 3. Feature envy | data class | 0 | 14178 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 2 | 2341 | 14178 | minor |
| 1668 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Lack of modularity and abstraction 5. Violation of Single Responsibility Principle 6. Inconsistent naming conventions 7. Hard-coded values 8. Use of nested conditional statements 9. Lack of encapsulation 10. Lack of error handling 11. Lack of comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class DirectExecutorService implements ExecutorService { static final DirectExecutorService INSTANCE = new DirectExecutorService(); private boolean isShutdown = false; @Override public void shutdown() { isShutdown = true; } @Override @Nonnull public List shutdownNow() { isShutdown = true; return Collections.emptyList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isShutdown; } @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) { return isShutdown; } @Override @Nonnull public Future submit(@Nonnull Callable task) { try { T result = task.call(); return new CompletedFuture<>(result, null); } catch (Exception e) { return new CompletedFuture<>(null, e); } } @Override @Nonnull public Future submit(@Nonnull Runnable task, T result) { task.run(); return new CompletedFuture<>(result, null); } @Override @Nonnull public Future submit(@Nonnull Runnable task) { task.run(); return new CompletedFuture<>(null, null); } @Override @Nonnull public List> invokeAll(@Nonnull Collection> tasks) { ArrayList> result = new ArrayList<>(); for (Callable task : tasks) { try { result.add(new CompletedFuture<>(task.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } return result; } @Override @Nonnull public List> invokeAll( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); Iterator> iterator = tasks.iterator(); ArrayList> result = new ArrayList<>(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { result.add(new CompletedFuture<>(callable.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } while (iterator.hasNext()) { iterator.next(); result.add(new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean isDone() { return false; } @Override public T get() { throw new CancellationException("Task has been cancelled."); } @Override public T get(long timeout, @Nonnull TimeUnit unit) { throw new CancellationException("Task has been cancelled."); } }); } return result; } @Override @Nonnull public T invokeAny(@Nonnull Collection> tasks) throws ExecutionException { Exception exception = null; for (Callable task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); } @Override public T invokeAny( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis(timeout); Exception exception = null; Iterator> iterator = tasks.iterator(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { return callable.call(); } catch (Exception e) { // ignore exception and try next exception = e; } } if (iterator.hasNext()) { throw new TimeoutException("Could not finish execution of tasks within time."); } else { throw new ExecutionException("No tasks finished successfully.", exception); } } @Override public void execute(@Nonnull Runnable command) { command.run(); } static class CompletedFuture implements Future { private final V value; private final Exception exception; CompletedFuture(V value, Exception exception) { this.value = value; this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public V get() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } else { return value; } } @Override public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException { return get(); } } } |
blob | Long method2 Feature envy3 Code duplication4 Lack of modularity and abstraction 5 Violation of Single Responsibility Principle 6 Inconsistent naming conventions 7 Hard-coded values 8 Use of nested conditional statements 9 Lack of encapsulation | t | f | f | . Long method2. Feature envy3. Code duplication4. Lack of modularity and abstraction 5. Violation of Single Responsibility Principle 6. Inconsistent naming conventions 7. Hard-coded values 8. Use of nested conditional statements 9. Lack of encapsulation | blob | 0 | 11626 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/DirectExecutorService.java/#L37-L252 | 2 | 1668 | 11626 | minor |
| 1820 | {"response": "YES I found bad smells", "detectedBadSmells": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class HttpsTokenInInterceptor extends AbstractPhaseInterceptor { HttpsTokenInInterceptor() { super(Phase.PRE_STREAM); addBefore(WSS4JStaxInInterceptor.class.getName()); } public void handleMessage(Message message) throws Fault { AssertionInfoMap aim = message.get(AssertionInfoMap.class); // extract Assertion information if (aim != null) { Collection ais = PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.HTTPS_TOKEN); boolean requestor = isRequestor(message); if (ais.isEmpty()) { if (!requestor) { try { assertNonHttpsTransportToken(message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } } return; } if (!requestor) { try { assertHttps(aim, ais, message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } // Store the TLS principal on the message context SecurityContext sc = message.get(SecurityContext.class); if (sc == null || sc.getUserPrincipal() == null) { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null && tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0 && (tlsInfo.getPeerCertificates()[0] instanceof X509Certificate) ) { X509Certificate cert = (X509Certificate)tlsInfo.getPeerCertificates()[0]; message.put( SecurityContext.class, createSecurityContext(cert.getSubjectX500Principal()) ); } } } else { //client side should be checked on the way out for (AssertionInfo ai : ais) { ai.setAsserted(true); } PolicyUtils.assertPolicy(aim, SPConstants.HTTP_DIGEST_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.HTTP_BASIC_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.REQUIRE_CLIENT_CERTIFICATE); } } } private void assertHttps( AssertionInfoMap aim, Collection ais, Message message ) throws XMLSecurityException { List securityEvents = getSecurityEventList(message); AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); for (AssertionInfo ai : ais) { boolean asserted = true; HttpsToken token = (HttpsToken)ai.getAssertion(); HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); Map> headers = getProtocolHeaders(message); if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpBasicAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Basic")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpBasicAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(true, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_BASIC_AUTHENTICATION)); } } if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpDigestAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Digest")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpDigestAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(false, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_DIGEST_AUTHENTICATION)); } } TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { if (token.getAuthenticationType() == HttpsToken.AuthenticationType.RequireClientCertificate) { if (tlsInfo.getPeerCertificates() == null || tlsInfo.getPeerCertificates().length == 0) { asserted = false; } else { PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.REQUIRE_CLIENT_CERTIFICATE)); } } if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } } else { asserted = false; } ai.setAsserted(asserted); if (asserted) { securityEvents.add(httpsTokenSecurityEvent); } } } // We might have an IssuedToken TransportToken private void assertNonHttpsTransportToken(Message message) throws XMLSecurityException { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } List securityEvents = getSecurityEventList(message); securityEvents.add(httpsTokenSecurityEvent); } } private List getSecurityEventList(Message message) { @SuppressWarnings("unchecked") List securityEvents = (List) message.getExchange().get(SecurityEvent.class.getName() + ".out"); if (securityEvents == null) { securityEvents = new ArrayList<>(); message.getExchange().put(SecurityEvent.class.getName() + ".out", securityEvents); } return securityEvents; } private SecurityContext createSecurityContext(final Principal p) { return new SecurityContext() { public Principal getUserPrincipal() { return p; } public boolean isUserInRole(String role) { return false; } }; } } |
blob | t | f | f | blob | 0 | 12094 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/HttpsTokenInterceptorProvider.java/#L191-L390 | 1 | 1820 | 12094 | major | ||
| 1721 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 11796 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 2 | 1721 | 11796 | critical |
| 3506 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7525 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 1 | 3506 | 7525 | minor | ||
| 2627 | YES I found bad smells. The bad smells are: 1. No documentation provided 2. No error handling or exception handling 3. No comments or explanation of code functionality 4. Instance variables not encapsulated properly 5. Incomplete constructor - requires additional parameters to be fully functional 6. Unclear naming of variables and methods 7. No validation of input parameters in constructor or methods 8. Inconsistent use of modifiers (e.g. final, private, etc.) 9. Inconsistent formatting/style (e.g. using tabs vs. spaces) 10. Duplicate code in superclass and subclass 11. Lack of encapsulation - instance variables are accessed directly in methods 12. No unit tests provided 13. No inheritance hierarchy explained 14. Possible violation of Java naming conventions for class names and interface names 15. Potential for mutable state in instance variables - no setter methods provided to modify values 16. No use of JavaDocs for documenting code 17. Possible violation of Single Responsibility Principle - class appears to have multiple responsibilities 18. Possible violation of Liskov Substitution Principle - subclass may not fully conform to the behavior of superclass 19. No use of public access modifier for interface methods 20. Potential for tight coupling between superclass and subclass. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | No documentation provided2 No error handling or exception handling3 No comments or explanation of code functionality4 Instance variables not encapsulated properly5 Incomplete constructor - requires additional parameters to be fully functional6 Unclear naming of variables and methods7 No validation of input parameters in constructor or methods8 Inconsistent use of modifiers (eg final, private, etc)9 Inconsistent formatting/style (eg using tabs vs spaces) | t | f | f | . No documentation provided2. No error handling or exception handling3. No comments or explanation of code functionality4. Instance variables not encapsulated properly5. Incomplete constructor - requires additional parameters to be fully functional6. Unclear naming of variables and methods7. No validation of input parameters in constructor or methods8. Inconsistent use of modifiers (e.g. final, private, etc.)9. Inconsistent formatting/style (e.g. using tabs vs. spaces) | data class | 0 | 15086 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 2627 | 15086 | major |
| 417 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4230 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 417 | 4230 | major |
| 1492 | YES I found bad smells the bad smells are: 1. Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive) 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive)2 Long method3 Feature envy | t | f | f | . Bad class name: TypeRefWithoutModifiersElements (not clear or descriptive)2. Long method3. Feature envy | data class | 0 | 11118 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1492 | 11118 | critical |
| 2360 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14236 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 2 | 2360 | 14236 | critical |
| 2485 | {"output": "YES I found bad smells", "the bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14608 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 1 | 2485 | 14608 | minor |
| 145 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public abstract class AbstractEntitiesRuntimeModule extends DefaultXbaseRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/xtext/idea/example/entities/Entities.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.idea.example.entities.Entities"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("entities"); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class bindIGrammarAccess() { return EntitiesGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISemanticSequencer() { return EntitiesSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISyntacticSequencer() { return EntitiesSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIParser() { return EntitiesParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIAntlrTokenFileProvider() { return EntitiesAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindLexer() { return InternalEntitiesLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider provideInternalEntitiesLexer() { return LexerProvider.create(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class bindEntitiesValidator() { return EntitiesValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public Class bindIBatchScopeProvider() { return EntitiesScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIScopeProviderDelegate(Binder binder) { binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(XImportSectionNamespaceScopeProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIgnoreCaseLinking(Binder binder) { binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIContainer$Manager() { return StateBasedContainerManager.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIAllContainersState$Provider() { return ResourceSetBasedAllContainersStateProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptions(Binder binder) { binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptionsPersisted(Binder binder) { binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class bindIFormatter2() { return EntitiesFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIQualifiedNameProvider() { return XbaseQualifiedNameProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindILocationInFileProvider() { return JvmLocationInFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIGlobalScopeProvider() { return TypesAwareDefaultGlobalScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindFeatureNameValidator() { return LogicalContainerAwareFeatureNameValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultBatchTypeResolver() { return LogicalContainerAwareBatchTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultReentrantTypeResolver() { return LogicalContainerAwareReentrantTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIResourceValidator() { return DerivedStateAwareResourceValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIJvmModelInferrer() { return EntitiesJvmModelInferrer.class; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 1809 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities/src-gen/org/eclipse/xtext/idea/example/entities/AbstractEntitiesRuntimeModule.java/#L76-L249 | 1 | 145 | 1809 | minor |
| 2140 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13264 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 2140 | 13264 | minor |
| 924 | {"response": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Not specified | f | f | f | false | 0 | 8307 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 924 | 8307 | minor | |
| 739 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class CancelableThread extends Thread { protected boolean running = true; protected boolean canceled = false; public synchronized final boolean isRunning() { return running; } public synchronized final void setRunning(boolean running) { this.running = running; } /** * Subclasses shouldn't do any potentially conflicting UI work before * checking to see if the thread has been canceled. */ public synchronized final boolean isCanceled() { return canceled; } public synchronized final void cancel() { this.canceled = true; } /** * Cancels the thread given if it's running. */ public static void cancelThread(CancelableThread thread) { if ( thread != null ) { synchronized ( thread ) { if ( thread.isRunning() ) { thread.cancel(); } } } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 6968 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/CancelableThread.java/#L23-L61 | 1 | 739 | 6968 | minor |
| 294 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inappropriate naming 5. Use of magic numbers 6. Inconsistent formatting 7. Poor exception handling (throwing RuntimeException) 8. Use of static variables in an abstract class 9. Overcomplicated logic and conditionals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Inappropriate naming5 Use of magic numbers6 Inconsistent formatting7 Poor exception handling (throwing RuntimeException)8 Use of static variables in an abstract class9 Overcomplicated logic and conditionals | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inappropriate naming5. Use of magic numbers6. Inconsistent formatting7. Poor exception handling (throwing RuntimeException)8. Use of static variables in an abstract class9. Overcomplicated logic and conditionals | blob | 0 | 3086 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 2 | 294 | 3086 | critical |
| 2191 | {"response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13466 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 2 | 2191 | 13466 | minor |
| 105 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1384 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 2 | 105 | 1384 | major |
| 1243 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
blob | data class | t | t | f | data class | blob | 0 | 10415 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 1243 | 10415 | minor |
| 398 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 4066 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 398 | 4066 | critical |
| 2021 | YES I found bad smells the bad smells are: 7. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | 7 Feature envy | t | f | f | 7. Feature envy | long method | 0 | 12790 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 2021 | 12790 | major |
| 2023 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 12796 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 2023 | 12796 | major |
| 5444 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15311 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 1 | 5444 | 15311 | critical |
| 1472 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 11052 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 1 | 1472 | 11052 | minor |
| 1937 | YES, the bad smells are: 1. Long method 2. Feature envy 3. Unnecessary code repetition (e.g. repeated calls to getJvmMXBeans()) 4. The use of synchronized blocks and locks, which can lead to potential deadlocks and performance issues 5. Method chaining (e.g. printThreads() calling printMonitors()) 6. Poor exception handling (e.g. catching generic Exception and logging instead of handling specific exceptions) 7. Magic numbers (e.g. 4096, Integer.MAX_VALUE) 8. Lack of encapsulation and information hiding (e.g. directly accessing and modifying instance variables within synchronized methods) 9. Use of deprecated methods (e.g. Logger.throwing()) 10. Poor naming conventions (e.g. variables named "sb", "hsDiagnostic") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | Long method2 Feature envy3 Unnecessary code repetition (eg repeated calls to getJvmMXBeans())4 The use of synchronized blocks and locks, which can lead to potential deadlocks and performance issues5 Method chaining (eg printThreads() calling printMonitors())6 Poor exception handling (eg catching generic Exception and logging instead of handling specific exceptions)7 Magic numbers (eg 4096, IntegerMAX_VALUE)8 Lack of encapsulation and information hiding (eg directly accessing and modifying instance variables within synchronized methods)9 Use of deprecated methods (eg Loggerthrowing()) | t | f | f | . Long method2. Feature envy3. Unnecessary code repetition (e.g. repeated calls to getJvmMXBeans())4. The use of synchronized blocks and locks, which can lead to potential deadlocks and performance issues5. Method chaining (e.g. printThreads() calling printMonitors())6. Poor exception handling (e.g. catching generic Exception and logging instead of handling specific exceptions)7. Magic numbers (e.g. 4096, Integer.MAX_VALUE)8. Lack of encapsulation and information hiding (e.g. directly accessing and modifying instance variables within synchronized methods)9. Use of deprecated methods (e.g. Logger.throwing()) | blob | 0 | 12472 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 2 | 1937 | 12472 | critical |
| 4956 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 13562 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 4956 | 13562 | minor | ||
| 2025 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 12800 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 1 | 2025 | 12800 | minor |
| 1915 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServerFormatListPDU extends BaseElement { protected ClipboardState state; public ServerFormatListPDU(String id, ClipboardState state) { super(id); this.state = state; } @Override public void handleData(ByteBuffer buf, Link link) { if (verbose) System.out.println("[" + this + "] INFO: Data received: " + buf + "."); parseFormatNames(buf); buf.unref(); // Automatically send request for text-based data to insert it into local // clipboard ClipboardDataFormat textFormat = ClipboardDataFormat.findBestTextFormat(state.serverClipboardDataFormats); if (textFormat != null) { // Send response: OK sendFormatListParseResponse(true); // Request data sendFormatDataRequest(textFormat); } else { // Send response: FAIL, we are not interested in this data sendFormatListParseResponse(false); } } /** * The Format Data Request PDU is sent by the recipient of the Format List * PDU. It is used to request the data for one of the formats that was listed * in the Format List PDU. */ protected void sendFormatDataRequest(ClipboardDataFormat textFormat) { if (verbose) System.out.println("[" + this + "] INFO: Sending request for data in following format: " + textFormat + "."); // Store data format to parse server response later state.serverRequestedFormat = textFormat; ByteBuffer buf = new ByteBuffer(12, true); // Type buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_DATA_REQUEST); // Message flags buf.writeShortLE(0); // Length buf.writeIntLE(4); // ID of chosen format buf.writeIntLE(textFormat.id); buf.trimAtCursor(); pushDataToPad(STDOUT, buf); } /** * The Format List Response PDU is sent as a reply to the Format List PDU. It * is used to indicate whether processing of the Format List PDU was * successful. * * @param b */ protected void sendFormatListParseResponse(boolean ok) { ByteBuffer buf = new ByteBuffer(8, true); // Type buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_LIST_RESPONSE); // Message flags buf.writeShortLE((ok) ? ServerClipRdrChannelRouter.CB_RESPONSE_OK : ServerClipRdrChannelRouter.CB_RESPONSE_FAIL); // Length buf.writeIntLE(0); buf.trimAtCursor(); pushDataToPad(STDOUT, buf); } protected void parseFormatNames(ByteBuffer buf) { // Set will not be modified after creation, so there is no need to make it // synchronous. Map formats = new HashMap(); while (buf.cursor < buf.length) { int id = buf.readSignedIntLE(); String name; if (state.serverUseLongFormatNames) { // Long format names in Unicode name = buf.readVariableWideString(RdpConstants.CHARSET_16); } else { Boolean asciiNames = (Boolean)buf.getMetadata(ServerClipRdrChannelRouter.ASCII_NAMES); if (asciiNames != null && asciiNames) { // Short format names in ASCII name = buf.readString(32, RdpConstants.CHARSET_8); } else { // Short format names in Unicode name = buf.readString(32, RdpConstants.CHARSET_16); } } // Store format in map by both ID and name (if name is not empty) formats.put(id, new ClipboardDataFormat(id, name)); if (name.length() > 0) formats.put(name, new ClipboardDataFormat(id, name)); } if (verbose) System.out.println("Server supports following formats for clipboard data: " + formats.values().toString() + "."); state.serverClipboardDataFormats = formats; } /** * Example. */ public static void main(String[] args) { // System.setProperty("streamer.Link.debug", "true"); System.setProperty("streamer.Element.debug", "true"); // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ byte[] packet = new byte[] { 0x02, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST (2) 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 (byte) 0xe0, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0xe0 = 224 bytes (byte) 0x8a, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc08a = 49290 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format" 0x45, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc145 = 49477 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x57, 0x00, 0x69, 0x00, 0x74, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x74, 0x00, 0x20, 0x00, 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x73, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format Without Objects" 0x43, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc143 = 49475 0x52, 0x00, 0x54, 0x00, 0x46, 0x00, 0x20, 0x00, 0x41, 0x00, 0x73, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "RTF As Text" 0x01, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 1 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0x0d = 13 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x04, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc004 = 49156 0x4e, 0x00, 0x61, 0x00, 0x74, 0x00, 0x69, 0x00, 0x76, 0x00, 0x65, 0x00, 0x00, 0x00, // "Native" 0x0e, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc00e = 49166 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x20, 0x00, 0x44, 0x00, 0x65, 0x00, 0x73, 0x00, 0x63, 0x00, 0x72, 0x00, 0x69, 0x00, 0x70, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Object Descriptor" 0x03, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 3 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x10, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 16 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x07, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 7 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" }; /* @formatter:on */ MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element router = new ServerClipRdrChannelRouter("router"); ClipboardState state = new ClipboardState(); state.serverUseLongFormatNames = true; Element format_list = new ServerFormatListPDU("format_list", state); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { // Format List Response PDU 0x03, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST_RESPONSE (3) 0x01, 0x00, // CLIPRDR_HEADER::msgFlags = 0x0001 = CB_RESPONSE_OK 0x00, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0 bytes }, new byte[] { // Format Data Request PDU 0x04, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_DATA_REQUEST (4) 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 0x04, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 4 bytes 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_FORMAT_DATA_REQUEST::requestedFormatId // = 0x0d })); Pipeline pipeline = new PipelineImpl("test"); pipeline.add(source, router, format_list, sink); pipeline.link("source", "router >format_list", "format_list", "sink"); pipeline.runMainLoop("source", STDOUT, false, false); // Check state if (!(state.serverClipboardDataFormats.containsKey(49475) && state.serverClipboardDataFormats.containsKey("Rich Text Format"))) throw new RuntimeException("Server format list packet parsed incorrectly."); } } |
blob | 1: long method | t | t | f | 1: long method | blob | 0 | 12407 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/services/console-proxy/rdpconsole/src/main/java/rdpclient/clip/ServerFormatListPDU.java/#L32-L237 | 1 | 1915 | 12407 | minor |
| 10 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 613 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 1 | 10 | 613 | minor |
| 1865 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12235 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 2 | 1865 | 12235 | major |
| 1771 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 11920 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 2 | 1771 | 11920 | minor |
| 2351 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14219 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 2 | 2351 | 14219 | minor |
| 1815 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteWasbDelegationTokenManager implements WasbDelegationTokenManager { /** * Configuration parameter name expected in the configuration * object to provide the url of the delegation token service to fetch the delegation tokens. */ public static final String KEY_DELEGATION_TOKEN_SERVICE_URLS = "fs.azure.delegation.token.service.urls"; /** * Configuration key to enable http retry policy for delegation token service calls. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY = "fs.azure.delegationtokenservice.http.retry.policy.enabled"; /** * Configuration key for delegation token service http retry policy spec. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY = "fs.azure.delegationtokenservice.http.retry.policy.spec"; /** * Default remote delegation token manager endpoint. */ private static final String DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT = "/tokenmanager/v1"; /** * Default for delegation token service http retry policy spec. */ private static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10,3,100,2"; private static final boolean DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = true; private static final Text WASB_DT_SERVICE_NAME = new Text("WASB_DT_SERVICE"); /** * Query parameter value for Getting delegation token http request */ private static final String GET_DELEGATION_TOKEN_OP = "GETDELEGATIONTOKEN"; /** * Query parameter value for renewing delegation token http request */ private static final String RENEW_DELEGATION_TOKEN_OP = "RENEWDELEGATIONTOKEN"; /** * Query parameter value for canceling the delegation token http request */ private static final String CANCEL_DELEGATION_TOKEN_OP = "CANCELDELEGATIONTOKEN"; /** * op parameter to represent the operation. */ private static final String OP_PARAM_KEY_NAME = "op"; /** * renewer parameter to represent the renewer of the delegation token. */ private static final String RENEWER_PARAM_KEY_NAME = "renewer"; /** * service parameter to represent the service which returns delegation tokens. */ private static final String SERVICE_PARAM_KEY_NAME = "service"; /** * token parameter to represent the delegation token. */ private static final String TOKEN_PARAM_KEY_NAME = "token"; private WasbRemoteCallHelper remoteCallHelper; private String[] dtServiceUrls; private boolean isSpnegoTokenCacheEnabled; public RemoteWasbDelegationTokenManager(Configuration conf) throws IOException { RetryPolicy retryPolicy = RetryUtils.getMultipleLinearRandomRetry(conf, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT); this.isSpnegoTokenCacheEnabled = conf.getBoolean(Constants.AZURE_ENABLE_SPNEGO_TOKEN_CACHE, true); remoteCallHelper = new SecureWasbRemoteCallHelper(retryPolicy, true, isSpnegoTokenCacheEnabled); this.dtServiceUrls = conf.getTrimmedStrings(KEY_DELEGATION_TOKEN_SERVICE_URLS); if (this.dtServiceUrls == null || this.dtServiceUrls.length <= 0) { throw new IOException( KEY_DELEGATION_TOKEN_SERVICE_URLS + " config not set" + " in configuration."); } } @Override public Token getDelegationToken( String renewer) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, GET_DELEGATION_TOKEN_OP) .addParameter(RENEWER_PARAM_KEY_NAME, renewer) .addParameter(SERVICE_PARAM_KEY_NAME, WASB_DT_SERVICE_NAME.toString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpGet.METHOD_NAME); return TokenUtils.toDelegationToken(JsonUtils.parse(responseBody)); } @Override public long renewDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, RENEW_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); Map parsedResp = JsonUtils.parse(responseBody); return ((Number) parsedResp.get("long")).longValue(); } @Override public void cancelDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, CANCEL_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); remoteCallHelper.makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); } } |
blob | \n1. long method | t | t | f | {"\\",n,1,.," ",l,o,n,g," ",m,e,t,h,o,d," "} | {"\\",n,1,.," ",o,n,g," ",m,t,h,o,d," "} | 0 | 12080 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/security/RemoteWasbDelegationTokenManager.java/#L39-L169 | 1 | 1815 | 12080 | minor |
| 1571 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11339 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 2 | 1571 | 11339 | minor |
| 479 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Long parameter list 5. Lack of encapsulation/visibility modifiers for some methods 6. Inconsistent formatting/spacing 7. Catch-all exception handling 8. Mixed levels of abstraction/complex logic in methods 9. Multiple return statements in a single method 10. Use of non-generic types in method declarations 11. Use of interface Injection instead of direct class injection 12. Unnecessary comments (e.g. "/* Override to handle config */") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Long parameter list5 Lack of encapsulation/visibility modifiers for some methods6 Inconsistent formatting/spacing7 Catch-all exception handling8 Mixed levels of abstraction/complex logic in methods9 Multiple return statements in a single method | t | f | f | . Long method2. Feature envy3. Duplicate code4. Long parameter list5. Lack of encapsulation/visibility modifiers for some methods6. Inconsistent formatting/spacing7. Catch-all exception handling8. Mixed levels of abstraction/complex logic in methods9. Multiple return statements in a single method | blob | 0 | 4625 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 2 | 479 | 4625 | minor |
| 2386 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | long method | t | t | f | long method | blob | 0 | 14349 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 1 | 2386 | 14349 | minor |
| 1195 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 10266 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 1195 | 10266 | minor |
| 481 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 4700 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 1 | 481 | 4700 | major |
| 986 | YES I found bad smells the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 8880 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 2 | 986 | 8880 | minor |
| 1814 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12067 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 1814 | 12067 | minor |
| 1890 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12309 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 1 | 1890 | 12309 | major |
| 1460 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11021 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1460 | 11021 | minor |
| 1789 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | t | f | f | long method | 0 | 11985 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 1 | 1789 | 11985 | minor | ||
| 618 | {"response": "YES, I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 6205 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 2 | 618 | 6205 | minor |
| 91 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Controller public class SignupController { private final SignupHelper signupHelper; @Inject public SignupController(AccountRepository accountRepository, SignedUpGateway gateway) { this.signupHelper = new SignupHelper(accountRepository, gateway); } /** * Render a signup form to the person as HTML in their web browser. */ @RequestMapping(value="/signup", method=RequestMethod.GET) public SignupForm signupForm(WebRequest request) { Connection connection = ProviderSignInUtils.getConnection(request); if (connection != null) { request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Greenhouse account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST); return SignupForm.fromProviderUser(connection.fetchUserProfile()); } else { return new SignupForm(); } } /** * Process a signup form submission. * Delegate to a {@link SignupHelper} to actually complete the signin transaction. * Redirects the new member to the application home page on successful sign-in. */ @RequestMapping(value="/signup", method=RequestMethod.POST) public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) { if (formBinding.hasErrors()) { return null; } boolean result = signupHelper.signup(form, formBinding, new SignupCallback() { public void postSignup(Account account) { ProviderSignInUtils.handlePostSignUp(account.getId().toString(), request); } }); return result ? "redirect:/" : null; } @RequestMapping(value="/signup", method=RequestMethod.POST, consumes="application/json") public ResponseEntity> signupFromApi(@RequestBody SignupForm form) { BindingResult formBinding = validate(form); // Temporary manual validation until SPR-9826 is fixed. if (formBinding.hasErrors()) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Validation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } boolean result = signupHelper.signup(form, formBinding); if (result) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account created"); return new ResponseEntity>(errorResponse, HttpStatus.CREATED); } else { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account creation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } } private BindException validate(SignupForm form) { BindException errors; errors = new BindException(form, "signupForm"); LazyValidatorFactory lvf = new LazyValidatorFactory(); Validator validator = new SpringValidatorAdapter(lvf.getValidator()); ValidationUtils.invokeValidator(validator, form, errors); return errors; } private List> getErrorsMap(BindingResult formBinding) { List fieldErrors = formBinding.getFieldErrors(); List> errors = new ArrayList>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map fieldErrorMap = new HashMap(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap); } return errors; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 1242 | https://github.com/spring-projects/greenhouse/blob/c7994183812150de971ef4a76c08d5b4631ab5d1/src/main/java/com/springsource/greenhouse/signup/SignupController.java/#L54-L143 | 1 | 91 | 1242 | minor |
| 2400 | YES I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | Feature envy | t | f | f | Feature envy | long method | 0 | 14379 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 2400 | 14379 | minor |
| 1081 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy. | data class | 0 | 9680 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 2 | 1081 | 9680 | major |
| 1539 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private final class SymbolProcessor implements FunctionVisitor, InstructionVisitorAdapter { private final SourceFunction function; private final LinkedList removeFromBlock = new LinkedList<>(); private int blockInstIndex = 0; private DbgValueInstruction lastDbgValue = null; private InstructionBlock currentBlock = null; private SymbolProcessor(SourceFunction function) { this.function = function; } @Override public void visit(InstructionBlock block) { currentBlock = block; lastDbgValue = null; for (blockInstIndex = 0; blockInstIndex < block.getInstructionCount(); blockInstIndex++) { block.getInstruction(blockInstIndex).accept(this); } if (!removeFromBlock.isEmpty()) { for (int i : removeFromBlock) { currentBlock.remove(i); } removeFromBlock.clear(); } } @Override public void visitInstruction(Instruction instruction) { final MDLocation loc = instruction.getDebugLocation(); if (loc != null) { final LLVMSourceLocation scope = cache.buildLocation(loc); if (scope != null) { instruction.setSourceLocation(scope); } } } @Override public void visit(VoidCallInstruction call) { final SymbolImpl callTarget = call.getCallTarget(); if (callTarget instanceof FunctionDeclaration) { switch (((FunctionDeclaration) callTarget).getName()) { case LLVM_DBG_DECLARE_NAME: handleDebugIntrinsic(call, true); return; case LLVM_DBG_ADDR_NAME: // dbg.declare and dbg.addr have the same interface and, for our purposes, // the same semantics handleDebugIntrinsic(call, true); return; case LLVM_DBG_VALUE_NAME: handleDebugIntrinsic(call, false); return; case LLVM_DEBUGTRAP_NAME: visitDebugTrap(call); return; } } visitInstruction(call); } private void visitDebugTrap(VoidCallInstruction call) { final DebugTrapInstruction trap = DebugTrapInstruction.create(call); currentBlock.set(blockInstIndex, trap); visitInstruction(trap); } private SourceVariable getVariable(VoidCallInstruction call, int index) { final SymbolImpl varSymbol = getArg(call, index); if (varSymbol instanceof MetadataSymbol) { final MDBaseNode mdLocal = ((MetadataSymbol) varSymbol).getNode(); final LLVMSourceSymbol symbol = cache.getSourceSymbol(mdLocal, false); return function.getLocal(symbol); } return null; } private void handleDebugIntrinsic(VoidCallInstruction call, boolean isDeclaration) { SymbolImpl value = getArg(call, LLVM_DBG_INTRINSICS_VALUE_ARGINDEX); if (value instanceof MetadataSymbol) { value = MDSymbolExtractor.getSymbol(((MetadataSymbol) value).getNode()); } if (value == null) { // this may happen if llvm optimizations removed a variable value = new NullConstant(MetaType.DEBUG); } else if (value instanceof ValueInstruction) { ((ValueInstruction) value).setSourceVariable(true); } else if (value instanceof FunctionParameter) { ((FunctionParameter) value).setSourceVariable(true); } int mdLocalArgIndex; int mdExprArgIndex; if (isDeclaration) { mdLocalArgIndex = LLVM_DBG_DECLARE_LOCALREF_ARGINDEX; mdExprArgIndex = LLVM_DBG_DECLARE_EXPR_ARGINDEX; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_NEW) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_NEW; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_NEW; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_OLD; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_OLD; } else { return; } final SourceVariable variable = getVariable(call, mdLocalArgIndex); if (variable == null) { // invalid or unsupported debug information // remove upper indices so we do not need to update the later ones removeFromBlock.addFirst(blockInstIndex); return; } final MDExpression expression = getExpression(call, mdExprArgIndex); if (ValueFragment.describesFragment(expression)) { variable.addFragment(ValueFragment.parse(expression)); } else { variable.addFullDefinition(); } if (isDeclaration) { final DbgDeclareInstruction dbgDeclare = new DbgDeclareInstruction(value, variable, expression); variable.addDeclaration(dbgDeclare); currentBlock.set(blockInstIndex, dbgDeclare); } else { long index = 0; if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { final SymbolImpl indexSymbol = call.getArgument(LLVM_DBG_VALUE_INDEX_ARGINDEX_OLD); final Long l = LLVMSymbolReadResolver.evaluateLongIntegerConstant(indexSymbol); if (l != null) { index = l; } } final DbgValueInstruction dbgValue = new DbgValueInstruction(value, variable, index, expression); if (dbgValue.equals(lastDbgValue)) { // at higher optimization levels llvm often duplicates the @llvm.dbg.value // intrinsic call, we remove it again to avoid unnecessary runtime overhead removeFromBlock.addFirst(blockInstIndex); } else { variable.addValue(dbgValue); currentBlock.set(blockInstIndex, dbgValue); lastDbgValue = dbgValue; } } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 11229 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/sulong/projects/com.oracle.truffle.llvm.parser/src/com/oracle/truffle/llvm/parser/metadata/debuginfo/DebugInfoFunctionProcessor.java/#L145-L308 | 2 | 1539 | 11229 | major |
| 1014 | { "output": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 9295 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 1014 | 9295 | minor |
| 1072 | YES I found bad smells the bad smells are: 1. Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy. 2. Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code. 3. Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class. 4. Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes. 5. Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy2 Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code3 Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class4 Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes5 Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors | t | f | f | . Feature envy: The EnsemblExonVO class extends EnsemblDBBaseVO, indicating a potential use of attributes and methods from the parent class, which could lead to feature envy.2. Duplicate code: The get and set methods for version, assemblyName, seqRegionName, and strand are all similar with only the attribute names being different, indicating a potential for duplicate code.3. Long class: The EnsemblExonVO class contains only attributes and get/set methods, making it a relatively large and potentially bloated class.4. Inappropriate naming: The name "EnsemblExonVO" does not accurately describe the purpose of the class and its attributes.5. Inconsistent formatting: The use of both annotations and getter/setter methods to specify JSON properties is inconsistent and could lead to confusion or potential errors. | data class | 0 | 9608 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 2 | 1072 | 9608 | major |
| 1500 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DeleteIndexAction implements ExpirationAction { private static final Logger logger = LoggerFactory.getLogger(DeleteIndexAction.class); private final PersistentProvenanceRepository repository; private final IndexConfiguration indexConfiguration; private final IndexManager indexManager; public DeleteIndexAction(final PersistentProvenanceRepository repo, final IndexConfiguration indexConfiguration, final IndexManager indexManager) { this.repository = repo; this.indexConfiguration = indexConfiguration; this.indexManager = indexManager; } @Override public File execute(final File expiredFile) throws IOException { // count the number of records and determine the max event id that we are deleting. final long numDeleted = 0; long maxEventId = -1L; try (final RecordReader reader = RecordReaders.newRecordReader(expiredFile, repository.getAllLogFiles(), Integer.MAX_VALUE)) { maxEventId = reader.getMaxEventId(); } catch (final IOException ioe) { logger.warn("Failed to obtain max ID present in journal file {}", expiredFile.getAbsolutePath()); } // remove the records from the index final List indexDirs = indexConfiguration.getIndexDirectories(expiredFile); for (final File indexingDirectory : indexDirs) { final Term term = new Term(FieldNames.STORAGE_FILENAME, LuceneUtil.substringBefore(expiredFile.getName(), ".")); boolean deleteDir = false; final EventIndexWriter writer = indexManager.borrowIndexWriter(indexingDirectory); try { final IndexWriter indexWriter = writer.getIndexWriter(); indexWriter.deleteDocuments(term); indexWriter.commit(); final int docsLeft = indexWriter.numDocs(); deleteDir = docsLeft <= 0; logger.debug("After expiring {}, there are {} docs left for index {}", expiredFile, docsLeft, indexingDirectory); } finally { indexManager.returnIndexWriter(writer); } // we've confirmed that all documents have been removed. Delete the index directory. if (deleteDir) { indexManager.removeIndex(indexingDirectory); indexConfiguration.removeIndexDirectory(indexingDirectory); deleteDirectory(indexingDirectory); logger.info("Removed empty index directory {}", indexingDirectory); } } // Update the minimum index to 1 more than the max Event ID in this file. if (maxEventId > -1L) { indexConfiguration.setMinIdIndexed(maxEventId + 1L); } logger.info("Deleted Indices for Expired Provenance File {} from {} index files; {} documents removed", expiredFile, indexDirs.size(), numDeleted); return expiredFile; } private void deleteDirectory(final File dir) { if (dir == null || !dir.exists()) { return; } final File[] children = dir.listFiles(); if (children == null) { return; } for (final File child : children) { if (child.isDirectory()) { deleteDirectory(child); } else if (!child.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", child.getAbsolutePath()); } } if (!dir.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", dir); } } @Override public boolean hasBeenPerformed(final File expiredFile) throws IOException { return false; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11132 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-provenance-repository-bundle/nifi-persistent-provenance-repository/src/main/java/org/apache/nifi/provenance/lucene/DeleteIndexAction.java/#L34-L122 | 2 | 1500 | 11132 | major |
| 1375 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AttributeUtils { public static Attribute[] readAttributes(DataInputStream dataInputstream, ConstantPool cpool) { try { int length = dataInputstream.readUnsignedShort(); if (length == 0) { return Attribute.NoAttributes; } Attribute[] attrs = new Attribute[length]; for (int i = 0; i < length; i++) { attrs[i] = Attribute.readAttribute(dataInputstream, cpool); } return attrs; } catch (IOException e) { throw new ClassFormatException("IOException whilst reading set of attributes: " + e.toString()); } } /** Write (serialize) a set of attributes into a specified output stream */ public static void writeAttributes(Attribute[] attributes, DataOutputStream file) throws IOException { if (attributes == null) { file.writeShort(0); } else { file.writeShort(attributes.length); for (int i = 0; i < attributes.length; i++) { attributes[i].dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SIGNATURE) { return (Signature) attributes[i]; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_CODE) { return (Code) attributes[i]; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { return (ExceptionTable) attributes[i]; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { return (ConstantValue) attributes[i]; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { for (int i = 0; i < attributes.length; i++) { attributes[i].accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { return true; } } return false; } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { return (SourceFile) attributes[i]; } } return null; } } |
blob | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers | blob | 0 | 10805 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java/#L9-L99 | 2 | 1375 | 10805 | major |
| 357 | YES I found bad smells The bad smells are: 1. Long method (toString method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ConfigFilePropertySource extends FilePropertySource { private IFile file; public ConfigFilePropertySource(IFile file) { super(file); this.file = file; } @Override public String toString() { return file.getFullPath().toString(); } } |
data class | Long method (toString method) | t | f | f | . Long method (toString method) | data class | 0 | 3677 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.beans.ui/src/org/springframework/ide/eclipse/beans/ui/model/properties/ChildBeanProperties.java/#L154-L166 | 2 | 357 | 3677 | major |
| 917 | {"answer": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract class RTFParser extends AbstractFilter { /** The current RTF group nesting level. */ public int level; private int state; private StringBuffer currentCharacters; private String pendingKeyword; // where keywords go while we // read their parameters private int pendingCharacter; // for the \'xx construct private long binaryBytesLeft; // in a \bin blob? ByteArrayOutputStream binaryBuf; private boolean[] savedSpecials; /** A stream to which to write warnings and debugging information * while parsing. This is set to System.out to log * any anomalous information to stdout. */ protected PrintStream warnings; // value for the 'state' variable private final int S_text = 0; // reading random text private final int S_backslashed = 1; // read a backslash, waiting for next private final int S_token = 2; // reading a multicharacter token private final int S_parameter = 3; // reading a token's parameter private final int S_aftertick = 4; // after reading \' private final int S_aftertickc = 5; // after reading \'x private final int S_inblob = 6; // in a \bin blob /** Implemented by subclasses to interpret a parameter-less RTF keyword. * The keyword is passed without the leading '/' or any delimiting * whitespace. */ public abstract boolean handleKeyword(String keyword); /** Implemented by subclasses to interpret a keyword with a parameter. * @param keyword The keyword, as with handleKeyword(String). * @param parameter The parameter following the keyword. */ public abstract boolean handleKeyword(String keyword, int parameter); /** Implemented by subclasses to interpret text from the RTF stream. */ public abstract void handleText(String text); public void handleText(char ch) { handleText(String.valueOf(ch)); } /** Implemented by subclasses to handle the contents of the \bin keyword. */ public abstract void handleBinaryBlob(byte[] data); /** Implemented by subclasses to react to an increase * in the nesting level. */ public abstract void begingroup(); /** Implemented by subclasses to react to the end of a group. */ public abstract void endgroup(); // table of non-text characters in rtf static final boolean[] rtfSpecialsTable; static { rtfSpecialsTable = noSpecialsTable.clone(); rtfSpecialsTable['\n'] = true; rtfSpecialsTable['\r'] = true; rtfSpecialsTable['{'] = true; rtfSpecialsTable['}'] = true; rtfSpecialsTable['\\'] = true; } public RTFParser() { currentCharacters = new StringBuffer(); state = S_text; pendingKeyword = null; level = 0; //warnings = System.out; specialsTable = rtfSpecialsTable; } // TODO: Handle wrapup at end of file correctly. public void writeSpecial(int b) throws IOException { write((char)b); } protected void warning(String s) { if (warnings != null) { warnings.println(s); } } public void write(String s) throws IOException { if (state != S_text) { int index = 0; int length = s.length(); while(index < length && state != S_text) { write(s.charAt(index)); index ++; } if(index >= length) return; s = s.substring(index); } if (currentCharacters.length() > 0) currentCharacters.append(s); else handleText(s); } @SuppressWarnings("fallthrough") public void write(char ch) throws IOException { boolean ok; switch (state) { case S_text: if (ch == '\n' || ch == '\r') { break; // unadorned newlines are ignored } else if (ch == '{') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } level ++; begingroup(); } else if(ch == '}') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } if (level == 0) throw new IOException("Too many close-groups in RTF text"); endgroup(); level --; } else if(ch == '\\') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } state = S_backslashed; } else { currentCharacters.append(ch); } break; case S_backslashed: if (ch == '\'') { state = S_aftertick; break; } if (!Character.isLetter(ch)) { char[] newstring = new char[1]; newstring[0] = ch; if (!handleKeyword(new String(newstring))) { warning("Unknown keyword: " + newstring + " (" + (byte)ch + ")"); } state = S_text; pendingKeyword = null; /* currentCharacters is already an empty stringBuffer */ break; } state = S_token; /* FALL THROUGH */ case S_token: if (Character.isLetter(ch)) { currentCharacters.append(ch); } else { pendingKeyword = currentCharacters.toString(); currentCharacters = new StringBuffer(); // Parameter following? if (Character.isDigit(ch) || (ch == '-')) { state = S_parameter; currentCharacters.append(ch); } else { ok = handleKeyword(pendingKeyword); if (!ok) warning("Unknown keyword: " + pendingKeyword); pendingKeyword = null; state = S_text; // Non-space delimiters get included in the text if (!Character.isWhitespace(ch)) write(ch); } } break; case S_parameter: if (Character.isDigit(ch)) { currentCharacters.append(ch); } else { /* TODO: Test correct behavior of \bin keyword */ if (pendingKeyword.equals("bin")) { /* magic layer-breaking kwd */ long parameter = Long.parseLong(currentCharacters.toString()); pendingKeyword = null; state = S_inblob; binaryBytesLeft = parameter; if (binaryBytesLeft > Integer.MAX_VALUE) binaryBuf = new ByteArrayOutputStream(Integer.MAX_VALUE); else binaryBuf = new ByteArrayOutputStream((int)binaryBytesLeft); savedSpecials = specialsTable; specialsTable = allSpecialsTable; break; } int parameter = Integer.parseInt(currentCharacters.toString()); ok = handleKeyword(pendingKeyword, parameter); if (!ok) warning("Unknown keyword: " + pendingKeyword + " (param " + currentCharacters + ")"); pendingKeyword = null; currentCharacters = new StringBuffer(); state = S_text; // Delimiters here are interpreted as text too if (!Character.isWhitespace(ch)) write(ch); } break; case S_aftertick: if (Character.digit(ch, 16) == -1) state = S_text; else { pendingCharacter = Character.digit(ch, 16); state = S_aftertickc; } break; case S_aftertickc: state = S_text; if (Character.digit(ch, 16) != -1) { pendingCharacter = pendingCharacter * 16 + Character.digit(ch, 16); ch = translationTable[pendingCharacter]; if (ch != 0) handleText(ch); } break; case S_inblob: binaryBuf.write(ch); binaryBytesLeft --; if (binaryBytesLeft == 0) { state = S_text; specialsTable = savedSpecials; savedSpecials = null; handleBinaryBlob(binaryBuf.toByteArray()); binaryBuf = null; } } } /** Flushes any buffered but not yet written characters. * Subclasses which override this method should call this * method before flushing * any of their own buffers. */ public void flush() throws IOException { super.flush(); if (state == S_text && currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } } /** Closes the parser. Currently, this simply does a flush(), * followed by some minimal consistency checks. */ public void close() throws IOException { flush(); if (state != S_text || level > 0) { warning("Truncated RTF file."); /* TODO: any sane way to handle termination in a non-S_text state? */ /* probably not */ /* this will cause subclasses to behave more reasonably some of the time */ while (level > 0) { endgroup(); level --; } } super.close(); } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 8249 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/rtf/RTFParser.java/#L41-L334 | 1 | 917 | 8249 | major |
| 2118 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13199 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 1 | 2118 | 13199 | major |
| 1249 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Feature envy | t | f | f | .Feature envy | data class | 0 | 10434 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 1249 | 10434 | major |
| 700 | { "error": "Unable to identify any code smells from the provided Java code." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Not specified | f | f | f | false | 0 | 6687 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 700 | 6687 | major | |
| 2629 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent formatting 5. Poor variable naming 6. Magic numbers/strings 7. Unused code 8. Nested if statements 9. Lack of proper exception handling 10. Unused imports 11. Incomplete comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } } |
blob | Long method2 Feature envy3 Duplicate code4 Inconsistent formatting5 Poor variable naming6 Magic numbers/strings7 Unused code8 Nested if statements9 Lack of proper exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent formatting5. Poor variable naming6. Magic numbers/strings7. Unused code8. Nested if statements9. Lack of proper exception handling | blob | 0 | 15089 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 | 2 | 2629 | 15089 | minor |
| 3130 | { "message": "YES I found bad smells", "bad smells are:": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 4236 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 2 | 3130 | 4236 | major |
| 18 | {"response": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } } |
blob | Not specified | f | f | f | false | 0 | 660 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 | 2 | 18 | 660 | critical | |
| 2063 | YES I found bad smells. The bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
blob | ) Long method2) Feature envy | t | f | f | ) Long method2) Feature envy | blob | 0 | 12977 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 2 | 2063 | 12977 | minor |
| 2591 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14999 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 2 | 2591 | 14999 | minor |
| 651 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6384 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 651 | 6384 | major |
| 310 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3205 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 1 | 310 | 3205 | critical |
| 2586 | YES I found bad smells the following bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Long parameter list 5. Too many constants 6. Unused code or commented out code 7. Excessive commenting 8. Unnecessary try catch blocks 9. Inconsistent formatting and naming conventions 10. Nested if statements and loops 11. Inefficient data structures 12. Code duplication within methods 13. Excessive use of static methods and variables 14. Inappropriate code comments 15. Potential for concurrency issues with non-threadsafe variables 16. Use of magic numbers and hardcoding 17. Confusing and unclear variable and method names 18. Combining unrelated functionality into one class 19. Inconsistent exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | Long method2 Feature envy3 Duplicated code4 Long parameter list5 Too many constants6 Unused code or commented out code7 Excessive commenting8 Unnecessary try catch blocks9 Inconsistent formatting and naming conventions | t | f | f | . Long method2. Feature envy3. Duplicated code4. Long parameter list5. Too many constants6. Unused code or commented out code7. Excessive commenting8. Unnecessary try catch blocks9. Inconsistent formatting and naming conventions | blob | 0 | 14989 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 2586 | 14989 | critical |
| 1160 | {"message": "YES I found bad smells", "bad smells are:":["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 10164 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 2 | 1160 | 10164 | major |
| 2107 | YES I found bad smells the bad smells are: 1. Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf. 2. Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own. 3. The use of deprecated methods, indicating that the code may need to be updated or refactored. 4. Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration. 5. Possible inconsistency in naming conventions for fields and methods (e.g. authorizations vs auths, topLevelIterators vs allIters). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf2 Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own3 The use of deprecated methods, indicating that the code may need to be updated or refactored4 Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration5 Possible inconsistency in naming conventions for fields and methods (eg authorizations vs auths, topLevelIterators vs allIters) | t | f | f | . Duplication of code in the constructor for the fields authorizations, conf, useSample, and sampleConf.2. Feature envy in the methods getTopLevelIterator and cloneWithSamplingEnabled, as they are manipulating the data of the iterator environment's fields instead of their own.3. The use of deprecated methods, indicating that the code may need to be updated or refactored.4. Long method with multiple responsibilities, as the class has both iterator environment related methods and methods for handling sampling and configuration.5. Possible inconsistency in naming conventions for fields and methods (e.g. authorizations vs auths, topLevelIterators vs allIters). | data class | 0 | 13177 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 2107 | 13177 | minor |
| 1989 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | Long method2 Feature Envy | t | f | f | . Long method2. Feature Envy | blob | 0 | 12678 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 1989 | 12678 | major |
| 1285 | { "message": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | blob | t | t | f | blob | data class | 0 | 10608 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 1285 | 10608 | critical |
| 1087 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 9710 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 1 | 1087 | 9710 | minor |
| 724 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: { Tuple2 val = arg0.next(); long valix = val._2 + 1; long rix = UtilFunctions.computeBlockIndex(valix, _brlen); int pos = UtilFunctions.computeCellInBlock(valix, _brlen); if( ix == null || ix.getRowIndex() != rix ) { if( ix !=null ) ret.add(new Tuple2<>(ix,mb)); long len = UtilFunctions.computeBlockSize(_rlen, rix, _brlen); ix = new MatrixIndexes(rix,1); mb = new MatrixBlock((int)len, 1, false); } mb.quickSetValue(pos, 0, val._1); } //flush last block if( mb!=null && mb.getNonZeros() != 0 ) ret.add(new Tuple2<>(ix,mb)); return ret.iterator(); } } private static class ConvertToBinaryBlockFunction2 implements PairFlatMapFunction>,MatrixIndexes,MatrixBlock> { private static final long serialVersionUID = -8638434373377180192L; private long _rlen = -1; private int _brlen = -1; public ConvertToBinaryBlockFunction2(long rlen, int brlen) { _rlen = rlen; _brlen = brlen; } public Iterator> call(Iterator> arg0) throws Exception { ArrayList> ret = new ArrayList<>(); MatrixIndexes ix = null; MatrixBlock mb = null; |
blob | Not specified | f | f | f | false | 0 | 6835 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDSortUtils.java/#L431-L475 | 1 | 724 | 6835 | minor | |
| 280 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3003 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 2 | 280 | 3003 | minor |
| 3588 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7922 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 3588 | 7922 | minor | ||
| 2899 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 2138 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 2 | 2899 | 2138 | minor | ||
| 1877 | { "message": "YES I found bad smells, the bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 12265 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 1877 | 12265 | critical |
| 1508 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11154 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 1508 | 11154 | major |
| 5046 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14099 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 2 | 5046 | 14099 | major |
| 3976 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 10433 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 3976 | 10433 | minor |
| 2303 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | f | f | f | data class | 0 | 14060 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 2303 | 14060 | major | ||
| 1319 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Service public class DepositAccountAssembler { private final PlatformSecurityContext context; private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsHelper savingsHelper; private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final StaffRepositoryWrapper staffRepository; private final FixedDepositProductRepository fixedDepositProductRepository; private final RecurringDepositProductRepository recurringDepositProductRepository; private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final SavingsAccountChargeAssembler savingsAccountChargeAssembler; private final FromJsonHelper fromApiJsonHelper; private final DepositProductAssembler depositProductAssembler; private final PaymentDetailAssembler paymentDetailAssembler; @Autowired public DepositAccountAssembler(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final ClientRepositoryWrapper clientRepository, final GroupRepositoryWrapper groupRepository, final StaffRepositoryWrapper staffRepository, final FixedDepositProductRepository fixedDepositProductRepository, final SavingsAccountRepositoryWrapper savingsAccountRepository, final SavingsAccountChargeAssembler savingsAccountChargeAssembler, final FromJsonHelper fromApiJsonHelper, final DepositProductAssembler depositProductAssembler, final RecurringDepositProductRepository recurringDepositProductRepository, final AccountTransfersReadPlatformService accountTransfersReadPlatformService, final PlatformSecurityContext context, final PaymentDetailAssembler paymentDetailAssembler) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.staffRepository = staffRepository; this.fixedDepositProductRepository = fixedDepositProductRepository; this.savingsAccountRepository = savingsAccountRepository; this.savingsAccountChargeAssembler = savingsAccountChargeAssembler; this.fromApiJsonHelper = fromApiJsonHelper; this.depositProductAssembler = depositProductAssembler; this.recurringDepositProductRepository = recurringDepositProductRepository; this.savingsHelper = new SavingsHelper(accountTransfersReadPlatformService); this.context = context; this.paymentDetailAssembler = paymentDetailAssembler; } /** * Assembles a new {@link SavingsAccount} from JSON details passed in * request inheriting details where relevant from chosen * {@link SavingsProduct}. */ public SavingsAccount assembleFrom(final JsonCommand command, final AppUser submittedBy, final DepositAccountType depositAccountType) { final JsonElement element = command.parsedJson(); final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); SavingsProduct product = null; if (depositAccountType.isFixedDeposit()) { product = this.fixedDepositProductRepository.findOne(productId); if (product == null) { throw new FixedDepositProductNotFoundException(productId); } } else if (depositAccountType.isRecurringDeposit()) { product = this.recurringDepositProductRepository.findOne(productId); if (product == null) { throw new RecurringDepositProductNotFoundException(productId); } } if (product == null) { throw new SavingsProductNotFoundException(productId); } Client client = null; Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; } if (group != null && client != null) { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } accountType = AccountType.JLG; if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); } else { interestRate = product.nominalAnnualInterestRate(); } SavingsCompoundingInterestPeriodType interestCompoundingPeriodType = null; final Integer interestPeriodTypeValue = command.integerValueOfParameterNamed(interestCompoundingPeriodTypeParamName); if (interestPeriodTypeValue != null) { interestCompoundingPeriodType = SavingsCompoundingInterestPeriodType.fromInt(interestPeriodTypeValue); } else { interestCompoundingPeriodType = product.interestCompoundingPeriodType(); } SavingsPostingInterestPeriodType interestPostingPeriodType = null; final Integer interestPostingPeriodTypeValue = command.integerValueOfParameterNamed(interestPostingPeriodTypeParamName); if (interestPostingPeriodTypeValue != null) { interestPostingPeriodType = SavingsPostingInterestPeriodType.fromInt(interestPostingPeriodTypeValue); } else { interestPostingPeriodType = product.interestPostingPeriodType(); } SavingsInterestCalculationType interestCalculationType = null; final Integer interestCalculationTypeValue = command.integerValueOfParameterNamed(interestCalculationTypeParamName); if (interestCalculationTypeValue != null) { interestCalculationType = SavingsInterestCalculationType.fromInt(interestCalculationTypeValue); } else { interestCalculationType = product.interestCalculationType(); } SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = command .integerValueOfParameterNamed(interestCalculationDaysInYearTypeParamName); if (interestCalculationDaysInYearTypeValue != null) { interestCalculationDaysInYearType = SavingsInterestCalculationDaysInYearType.fromInt(interestCalculationDaysInYearTypeValue); } else { interestCalculationDaysInYearType = product.interestCalculationDaysInYearType(); } BigDecimal minRequiredOpeningBalance = null; if (command.parameterExists(minRequiredOpeningBalanceParamName)) { minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); } else { minRequiredOpeningBalance = product.minRequiredOpeningBalance(); } Integer lockinPeriodFrequency = null; if (command.parameterExists(lockinPeriodFrequencyParamName)) { lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); } else { lockinPeriodFrequency = product.lockinPeriodFrequency(); } SavingsPeriodFrequencyType lockinPeriodFrequencyType = null; if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { Integer lockinPeriodFrequencyTypeValue = null; lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); if (lockinPeriodFrequencyTypeValue != null) { lockinPeriodFrequencyType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); } } else { lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); } boolean iswithdrawalFeeApplicableForTransfer = false; if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element, product.currency().getCode()); DepositAccountInterestRateChart accountChart = null; InterestRateChart productChart = null; if (command.parameterExists(chartIdParamName)) { Long chartId = command.longValueOfParameterNamed(chartIdParamName); productChart = product.findChart(chartId); } else { productChart = product.applicableChart(submittedOnDate); } if (productChart != null) { accountChart = DepositAccountInterestRateChart.from(productChart); } boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); if(withHoldTax && product.getTaxGroup() == null){ throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } SavingsAccount account = null; if (depositAccountType.isFixedDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((FixedDepositProduct) product).depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); FixedDepositAccount fdAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(fdAccount); fdAccount.validateDomainRules(); account = fdAccount; } else if (depositAccountType.isRecurringDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((RecurringDepositProduct) product) .depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); final DepositProductRecurringDetail prodRecurringDetail = ((RecurringDepositProduct) product).depositRecurringDetail(); final DepositAccountRecurringDetail accountRecurringDetail = this.assembleAccountRecurringDetail(command, prodRecurringDetail.recurringDetail()); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountRecurringDetail, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(rdAccount); accountRecurringDetail.updateAccountReference(rdAccount); rdAccount.validateDomainRules(); account = rdAccount; } if (account != null) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(), depositAccountType.resourceName()); } return account; } public SavingsAccount assembleFrom(final Long savingsId, DepositAccountType depositAccountType) { final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId, depositAccountType); account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure .depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, productPreClosure); final DepositTermDetail updatedProductTerm = this.depositProductAssembler.assembleDepositTermDetail(command, productTerm); final BigDecimal depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName); final Integer depositPeriod = command.integerValueOfParameterNamed(depositPeriodParamName); final Integer depositPeriodFrequencyId = command.integerValueOfParameterNamed(depositPeriodFrequencyIdParamName); final SavingsPeriodFrequencyType depositPeriodFrequency = SavingsPeriodFrequencyType.fromInt(depositPeriodFrequencyId); final SavingsAccount account = null; final LocalDate expectedFirstDepositOnDate = command.localDateValueOfParameterNamed(expectedFirstDepositOnDateParamName); final Boolean trasferInterest = command.booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName); // calculate maturity amount final BigDecimal maturityAmount = null;// calculated and updated in // account final LocalDate maturityDate = null;// calculated and updated in account final DepositAccountOnClosureType accountOnClosureType = null; return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest); } public DepositAccountRecurringDetail assembleAccountRecurringDetail(final JsonCommand command, final DepositRecurringDetail prodRecurringDetail) { final BigDecimal recurringDepositAmount = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); boolean isMandatoryDeposit; boolean allowWithdrawal; boolean adjustAdvanceTowardsFuturePayments; boolean isCalendarInherited; if (command.parameterExists(isMandatoryDepositParamName)) { isMandatoryDeposit = command.booleanObjectValueOfParameterNamed(isMandatoryDepositParamName); } else { isMandatoryDeposit = prodRecurringDetail.isMandatoryDeposit(); } if (command.parameterExists(allowWithdrawalParamName)) { allowWithdrawal = command.booleanObjectValueOfParameterNamed(allowWithdrawalParamName); } else { allowWithdrawal = prodRecurringDetail.allowWithdrawal(); } if (command.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName)) { adjustAdvanceTowardsFuturePayments = command.booleanObjectValueOfParameterNamed(adjustAdvanceTowardsFuturePaymentsParamName); } else { adjustAdvanceTowardsFuturePayments = prodRecurringDetail.adjustAdvanceTowardsFuturePayments(); } if (command.parameterExists(isCalendarInheritedParamName)) { isCalendarInherited = command.booleanObjectValueOfParameterNamed(isCalendarInheritedParamName); } else { isCalendarInherited = false; } final DepositRecurringDetail depositRecurringDetail = DepositRecurringDetail.createFrom(isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments); final DepositAccountRecurringDetail depositAccountRecurringDetail = DepositAccountRecurringDetail.createNew(recurringDepositAmount, depositRecurringDetail, null, isCalendarInherited); return depositAccountRecurringDetail; } public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = this.fromApiJsonHelper.parse(json); final Collection savingsAccountTransactions = new ArrayList<>(); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale); if (element.isJsonObject()) { if (topLevelJsonElement.has(bulkSavingsDueTransactionsParamName) && topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); } final SavingsAccountTransactionDTO savingsAccountTransactionDTO = new SavingsAccountTransactionDTO(formatter, transactionDate, dueAmount, detail, new Date(), savingsId, user, depositAccountType); savingsAccountTransactions.add(savingsAccountTransactionDTO); } } } return savingsAccountTransactions; } private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { user = this.context.getAuthenticatedUserIfPresent(); } return user; } } |
blob | data class | t | t | f | data class | blob | 0 | 10693 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java/#L107-L472 | 1 | 1319 | 10693 | major |
| 4001 | { "output": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Blob" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | 1: blob, 2: long method | t | t | f | 1: blob, 2: long method | feature envy | 0 | 10574 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 4001 | 10574 | major |
| 87 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
blob | Not specified | f | f | f | false | 0 | 1218 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 87 | 1218 | critical | |
| 764 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7134 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 2 | 764 | 7134 | major |
| 812 | YES I found bad smells the bad smells are: 1. Large method 2. Long parameters list 3. Duplicate code 4. Comments 5. Nested conditional statements 6. Magic numbers (e.g. "UTF-8") 7. Use of deprecated methods (e.g. "Files.copy") 8. Poor exception handling (e.g. suppressing exceptions, re-throwing exceptions) 9. Use of return statements instead of breaking out of loops 10. Overuse of print statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ICEDocCleaner { public static void main(String[] args) throws IOException { // Get a handle on the file System.out.println("Enter full filepath: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String path = br.readLine(); if (path.contains("exit")) { return; } File javaFile = new File(path); if (javaFile != null && javaFile.exists() && javaFile.isFile()) { System.out.println("File found, beginning cleaning..."); FileInputStream inputStream = null; Scanner scanner = null; StringBuilder sb = null; try { // Set up a scanner (should be more efficient than Files.nio for very big files) inputStream = new FileInputStream(javaFile); scanner = new Scanner(inputStream, "UTF-8"); String line = ""; sb = new StringBuilder(); while (scanner.hasNextLine() && (line = scanner.nextLine()) != null) { if (line.matches("\\s*\\*\\s*\\s*") || line.matches("\\s*\\*\\s*\\s*") || line.matches("\\s*// (begin|end)-user-code\\s*") || line.contains("@generated") || line.contains("UML to Java")) { // Skip over the line continue; } else { // Append the line to the StringBuilder sb.append(line + "\n"); } } System.out.println("Done cleaning."); // Note that Scanner suppresses exceptions, throw manually if (scanner.ioException() != null) { throw scanner.ioException(); } } finally { // Close this MF dooown if (inputStream != null) { inputStream.close(); } if (scanner != null) { scanner.close(); } } // Create a backup file in case something goes wrong int fileExtIndex = javaFile.getPath().lastIndexOf("."); String bakFilePath = javaFile.getPath().substring(0, fileExtIndex) + "_bak" + javaFile.getPath().substring(fileExtIndex); File bakFile = new File(bakFilePath); if (bakFile.exists()) { bakFile.delete(); } Files.copy(javaFile.toPath(), bakFile.toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("Creating back-up file... (will delete on successful exit)\n" + bakFile.getPath()); // Overwrite the original file BufferedWriter writer = new BufferedWriter(new FileWriter(javaFile)); writer.write(sb.toString()); System.out.println("Overwriting original file..."); if (writer != null) { writer.close(); } System.out.println("Process complete!"); bakFile.deleteOnExit(); } else { System.out.println("Could not find file."); main(args); } // k bai. return; } } |
blob | Large method2 Long parameters list3 Duplicate code4 Comments5 Nested conditional statements6 Magic numbers (eg "UTF-8")7 Use of deprecated methods (eg "Filescopy")8 Poor exception handling (eg suppressing exceptions, re-throwing exceptions)9 Use of return statements instead of breaking out of loops | t | f | f | . Large method2. Long parameters list3. Duplicate code4. Comments5. Nested conditional statements6. Magic numbers (e.g. "UTF-8")7. Use of deprecated methods (e.g. "Files.copy")8. Poor exception handling (e.g. suppressing exceptions, re-throwing exceptions)9. Use of return statements instead of breaking out of loops | blob | 0 | 7652 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/utils/ICEDocCleaner/src/ICEDocCleaner.java/#L36-L131 | 2 | 812 | 7652 | major |
| 2701 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | long method | t | t | f | long method | blob | 0 | 15329 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 2701 | 15329 | minor |
| 1430 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Not specified | f | f | f | false | 0 | 10952 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 1430 | 10952 | major | |
| 3923 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10270 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 3923 | 10270 | minor |
| 1335 | YES I found bad smells the bad smells are: 1. Duplicate Code (same default constructor defined in class and commented out) 2. Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2) 3. Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention) 4. Magic Number (package_id is assigned 0 without any explanation) 5. Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | Duplicate Code (same default constructor defined in class and commented out)2 Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2)3 Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention)4 Magic Number (package_id is assigned 0 without any explanation)5 Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | t | f | f | . Duplicate Code (same default constructor defined in class and commented out)2. Inconsistent Formatting (commented out constructor is indented with 4 spaces instead of 2)3. Inconsistent Naming (package_name and package_id variables not following standard camelCase naming convention)4. Magic Number (package_id is assigned 0 without any explanation)5. Feature Envy (package_id is being modified and used within the class, despite it being a parameter for the constructor) | data class | 0 | 10724 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 2 | 1335 | 10724 | critical |
| 299 | { "response": "YES I found bad smells", "detectedBadSmells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3147 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 1 | 299 | 3147 | minor |
| 452 | YES, I found bad smells the bad smells are: Long method, Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static TimeOfYear fromDateTime(DateTime dateTime) { DateTime nextYear = dateTime.plusYears(1); // This turns February 29 into February 28. TimeOfYear instance = new TimeOfYear(); instance.timeString = String.format( "%02d %02d %08d", nextYear.getMonthOfYear(), nextYear.getDayOfMonth(), nextYear.getMillisOfDay()); return instance; } |
feature envy | Long method, Message chains | t | f | f | Long method, Message chains | feature envy | 0 | 4409 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/common/TimeOfYear.java/#L61-L70 | 2 | 452 | 4409 | minor |
| 1022 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | long method | t | t | f | long method | blob | 0 | 9352 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1022 | 9352 | major |
| 1457 | private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.class, org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.Builder.class); } // Construct using org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); guaranteedTaskCount_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto getDefaultInstanceForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance(); } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto build() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto buildPartial() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = new org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.guaranteedTaskCount_ = guaranteedTaskCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) { return mergeFrom((org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto other) { if (other == org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance()) return this; if (other.hasGuaranteedTaskCount()) { setGuaranteedTaskCount(other.getGuaranteedTaskCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 guaranteed_task_count = 1; private int guaranteedTaskCount_ ; /** * optional int32 guaranteed_task_count = 1; */ public boolean hasGuaranteedTaskCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int32 guaranteed_task_count = 1; */ public int getGuaranteedTaskCount() { return guaranteedTaskCount_; } /** * optional int32 guaranteed_task_count = 1; */ public Builder setGuaranteedTaskCount(int value) { bitField0_ |= 0x00000001; guaranteedTaskCount_ = value; onChanged(); return this; } /** * optional int32 guaranteed_task_count = 1; */ public Builder clearGuaranteedTaskCount() { bitField0_ = (bitField0_ & ~0x00000001); guaranteedTaskCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:UpdateQueryRequestProto) } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11016 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/llap-common/src/gen/protobuf/gen-java/org/apache/hadoop/hive/llap/plugin/rpc/LlapPluginProtocolProtos.java/#L286-L435 | 2 | 1457 | 11016 | minor |
| 1138 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10070 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1138 | 10070 | major |
| 1890 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Unused imports 4. Unnecessary comments 5. Duplicate code 6. Use of generic type "Class" instead of specific data type 7. Use of primitive types instead of data structures like HashMap 8. Multiple responsibilities within the same class 9. Poor exception handling 10. Poor variable naming 11. Lack of modularity 12. High coupling 13. Low cohesion 14. Use of static fields 15. Use of magic numbers 16. Lack of proper spacing and formatting 17. Hard-coded values instead of constants 18. Poor error handling 19. Use of deprecated code 20. Poor use of inheritance and polymorphism 21. Lack of documentation and comments 22. Inconsistent naming conventions 23. Use of multiple if-else statements 24. Use of unused variables and parameters 25. Poor code structure and organization. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | Long method2 Feature envy3 Unused imports4 Unnecessary comments 5 Duplicate code 6 Use of generic type "Class" instead of specific data type 7 Use of primitive types instead of data structures like HashMap 8 Multiple responsibilities within the same class 9 Poor exception handling | t | f | f | . Long method2. Feature envy3. Unused imports4. Unnecessary comments 5. Duplicate code 6. Use of generic type "Class" instead of specific data type 7. Use of primitive types instead of data structures like HashMap 8. Multiple responsibilities within the same class 9. Poor exception handling | blob | 0 | 12309 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 2 | 1890 | 12309 | major |
| 2332 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14155 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 2 | 2332 | 14155 | major |
| 1403 | { "output": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | f | f | f | data class | 0 | 10864 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 1 | 1403 | 10864 | major | ||
| 3579 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 7895 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 2 | 3579 | 7895 | critical |
| 1166 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10184 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 1166 | 10184 | minor |
| 627 | YES I found bad smells. the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 6267 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 2 | 627 | 6267 | minor |
| 1750 | YES I found bad smells the bad smells are: 1. Feature envy 2. Data clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | Feature envy2 Data clumps | t | f | f | . Feature envy2. Data clumps | data class | 0 | 11858 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 1750 | 11858 | minor |
| 273 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2935 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 273 | 2935 | major |
| 3610 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8057 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 2 | 3610 | 8057 | minor |
| 180 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
blob | long method | t | t | f | long method | blob | 0 | 2063 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 180 | 2063 | major |
| 509 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 5182 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 | 1 | 509 | 5182 | major |
| 1666 | { "response": "YES I found bad smells", "bad smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | t | f | f | feature envy | 0 | 11623 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1666 | 11623 | minor | ||
| 1736 | YES I found bad smells, the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11827 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 2 | 1736 | 11827 | minor |
| 249 | {"message": "YES I found bad smells, the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2663 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 2 | 249 | 2663 | major |
| 946 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 8494 | https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 | 1 | 946 | 8494 | major |
| 1617 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 11475 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 1617 | 11475 | major |
| 2370 | { "output": "YES I found bad smells, the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 14305 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 1 | 2370 | 14305 | minor |
| 1089 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication (use of similar code in multiple methods) 4. Use of abbreviations (e.g. "mc" for "modCount", "e" for "element") that make the code less readable 5. Redundant code (e.g. checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method) 6. Non-descriptive variable names (e.g. "e" for "element", "mc" for "modCount") 7. Mixing of responsibilities (e.g. the EntrySet class is responsible for both containing entries and detecting concurrent modifications) 8. Unused or redundant comments (e.g. the comment above forEach() method) 9. Use of non-standard formatting conventions (e.g. use of "_" in variable names, lack of indentation) 10. Lack of error handling for possible NullPointerException in some methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
data class | Long method2 Feature envy3 Code duplication (use of similar code in multiple methods)4 Use of abbreviations (eg "mc" for "modCount", "e" for "element") that make the code less readable5 Redundant code (eg checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method)6 Non-descriptive variable names (eg "e" for "element", "mc" for "modCount")7 Mixing of responsibilities (eg the EntrySet class is responsible for both containing entries and detecting concurrent modifications)8 Unused or redundant comments (eg the comment above forEach() method)9 Use of non-standard formatting conventions (eg use of "_" in variable names, lack of indentation) | t | f | f | . Long method2. Feature envy3. Code duplication (use of similar code in multiple methods)4. Use of abbreviations (e.g. "mc" for "modCount", "e" for "element") that make the code less readable5. Redundant code (e.g. checking for null "action" parameter in forEach() method when it is already checked in the spliterator() method)6. Non-descriptive variable names (e.g. "e" for "element", "mc" for "modCount")7. Mixing of responsibilities (e.g. the EntrySet class is responsible for both containing entries and detecting concurrent modifications)8. Unused or redundant comments (e.g. the comment above forEach() method)9. Use of non-standard formatting conventions (e.g. use of "_" in variable names, lack of indentation) | data class | 0 | 9716 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 2 | 1089 | 9716 | minor |
| 87 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 1218 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 87 | 1218 | critical |
| 263 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class DoubleTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; DoubleTreeWriter(int columnId, TypeDescription schema, StreamFactory writer, boolean nullable) throws IOException { super(columnId, schema, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Datum datum) throws IOException { super.write(datum); if (datum != null && datum.isNotNull()) { double val = datum.asFloat8(); indexStatistics.updateDouble(val); if (createBloomFilter) { bloomFilter.addDouble(val); } utils.writeDouble(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2855 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/thirdparty/orc/WriterImpl.java/#L1041-L1082 | 1 | 263 | 2855 | minor |
| 31 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void displayWarning(final String message) { notificationMessage.showNotification(SPUIStyleDefinitions.SP_NOTIFICATION_WARNING_MESSAGE_STYLE, null, message, true); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 729 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/UINotification.java/#L52-L55 | 1 | 31 | 729 | minor |
| 2896 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WordMedian extends Configured implements Tool { private double median = 0; private final static IntWritable ONE = new IntWritable(1); /** * Maps words from line of text into a key-value pair; the length of the word * as the key, and 1 as the value. */ public static class WordMedianMapper extends Mapper { private IntWritable length = new IntWritable(); /** * Emits a key-value pair for counting the word. Outputs are (IntWritable, * IntWritable). * * @param value * This will be a line of text coming in from our input file. */ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { String string = itr.nextToken(); length.set(string.length()); context.write(length, ONE); } } } /** * Performs integer summation of all the values for each key. */ public static class WordMedianReducer extends Reducer { private IntWritable val = new IntWritable(); /** * Sums all the individual values within the iterator and writes them to the * same key. * * @param key * This will be a length of a word that was read. * @param values * This will be an iterator of all the values associated with that * key. */ public void reduce(IntWritable key, Iterable values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } val.set(sum); context.write(key, val); } } /** * This is a standard program to read and find a median value based on a file * of word counts such as: 1 456, 2 132, 3 56... Where the first values are * the word lengths and the following values are the number of times that * words of that length appear. * * @param path * The path to read the HDFS file from (part-r-00000...00001...etc). * @param medianIndex1 * The first length value to look for. * @param medianIndex2 * The second length value to look for (will be the same as the first * if there are an even number of words total). * @throws IOException * If file cannot be found, we throw an exception. * */ private double readAndFindMedian(String path, int medianIndex1, int medianIndex2, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); Path file = new Path(path, "part-r-00000"); if (!fs.exists(file)) throw new IOException("Output not found!"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8)); int num = 0; String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); // grab length String currLen = st.nextToken(); // grab count String lengthFreq = st.nextToken(); int prevNum = num; num += Integer.parseInt(lengthFreq); if (medianIndex2 >= prevNum && medianIndex1 <= num) { System.out.println("The median is: " + currLen); br.close(); return Double.parseDouble(currLen); } else if (medianIndex2 >= prevNum && medianIndex1 < num) { String nextCurrLen = st.nextToken(); double theMedian = (Integer.parseInt(currLen) + Integer .parseInt(nextCurrLen)) / 2.0; System.out.println("The median is: " + theMedian); br.close(); return theMedian; } } } finally { if (br != null) { br.close(); } } // error, no median found return -1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new WordMedian(), args); } @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: wordmedian "); return 0; } setConf(new Configuration()); Configuration conf = getConf(); @SuppressWarnings("deprecation") Job job = new Job(conf, "word median"); job.setJarByClass(WordMedian.class); job.setMapperClass(WordMedianMapper.class); job.setCombinerClass(WordMedianReducer.class); job.setReducerClass(WordMedianReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean result = job.waitForCompletion(true); // Wait for JOB 1 -- get middle value to check for Median long totalWords = job.getCounters() .getGroup(TaskCounter.class.getCanonicalName()) .findCounter("MAP_OUTPUT_RECORDS", "Map output records").getValue(); int medianIndex1 = (int) Math.ceil((totalWords / 2.0)); int medianIndex2 = (int) Math.floor((totalWords / 2.0)); median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf); return (result ? 0 : 1); } public double getMedian() { return median; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 2130 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/WordMedian.java/#L43-L212 | 2 | 2896 | 2130 | minor |
| 2389 | { "input_code": "TODO: Java code provided by the user", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | Long Method, Feature Envy | false | 0 | 14353 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/THBaseService.java/#L12256-L12314 | 1 | 2389 | 14353 | major | |
| 832 | {"message": "YES I found bad smells the bad smells are: 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component("aws-ddbstream") public class DdbStreamComponent extends DefaultComponent { @Metadata private String accessKey; @Metadata private String secretKey; @Metadata private String region; @Metadata(label = "advanced") private DdbStreamConfiguration configuration; public DdbStreamComponent() { this(null); } public DdbStreamComponent(CamelContext context) { super(context); this.configuration = new DdbStreamConfiguration(); registerExtension(new DdbStreamComponentVerifierExtension()); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { DdbStreamConfiguration configuration = this.configuration.copy(); configuration.setTableName(remaining); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Table name must be specified."); } configuration.setTableName(remaining); if (ObjectHelper.isEmpty(configuration.getAccessKey())) { setAccessKey(accessKey); } if (ObjectHelper.isEmpty(configuration.getSecretKey())) { setSecretKey(secretKey); } if (ObjectHelper.isEmpty(configuration.getRegion())) { setRegion(region); } if (configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("amazonDDBStreamsClient or accessKey and secretKey must be specified"); } DdbStreamEndpoint endpoint = new DdbStreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); return endpoint; } public DdbStreamConfiguration getConfiguration() { return configuration; } /** * The AWS DDB stream default configuration */ public void setConfiguration(DdbStreamConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return configuration.getAccessKey(); } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { configuration.setAccessKey(accessKey); } public String getSecretKey() { return configuration.getSecretKey(); } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { configuration.setSecretKey(secretKey); } public String getRegion() { return configuration.getRegion(); } /** * Amazon AWS Region */ public void setRegion(String region) { configuration.setRegion(region); } } |
blob | 2. feature envy | t | t | f | 2. feature envy | blob | 0 | 7739 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamComponent.java/#L28-L122 | 1 | 832 | 7739 | minor |
| 108 | {"response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1440 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 108 | 1440 | minor |
| 2324 | YES I found bad smells the bad smells are: 1. Long method 2. LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3. Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4. Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5. Inconsistent naming conventions 6. Unsupported operations should not be publicly accessible 7. Poorly structured and confusing logic in the put method 8. The put method is doing more than one thing and should be split into smaller methods 9. Collection interface is unnecessarily implemented 10. Inefficient use of data structures, LinkedList and ArrayList are being used when other data structures might be more appropriate 11. Nested loops and conditional statements can be hard to follow and difficult to debug 12. Lack of comments and documentation, making it hard for others to understand the code 13. Code duplication, specifically in the finishWriting and finishReading methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | Long method 2 LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3 Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4 Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5 Inconsistent naming conventions 6 Unsupported operations should not be publicly accessible 7 Poorly structured and confusing logic in the put method 8 The put method is doing more than one thing and should be split into smaller methods 9 Collection interface is unnecessarily implemented | t | f | f | . Long method 2. LimitedSizeDataCollection class is not domain specific, it has no clear purpose or responsibility 3. Writing and reading boolean variables are not used effectively and could cause issues with access to the data 4. Excessive use of volatile keyword could indicate a lack of understanding of threads and synchronization 5. Inconsistent naming conventions 6. Unsupported operations should not be publicly accessible 7. Poorly structured and confusing logic in the put method 8. The put method is doing more than one thing and should be split into smaller methods 9. Collection interface is unnecessarily implemented | data class | 0 | 14136 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 2 | 2324 | 14136 | minor |
| 1023 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9353 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1023 | 9353 | major |
| 133 | {"message": "YES I found bad smells", "bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnnotPage extends ContactsDisplayPage { @SpringBean private ContactDao dao; @Override protected ContactDataProvider getDataProvider() { return new ProxyDataProvider(dao); } } |
data class | blob | t | t | f | blob | data class | 0 | 1634 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-examples/src/main/java/org/apache/wicket/examples/spring/annot/web/AnnotPage.java/#L27-L37 | 1 | 133 | 1634 | minor |
| 1571 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11339 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 1 | 1571 | 11339 | minor |
| 1471 | { "message": "YES I found bad smells", "the bad smells are:": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11050 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 2 | 1471 | 11050 | critical |
| 263 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class DoubleTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; DoubleTreeWriter(int columnId, TypeDescription schema, StreamFactory writer, boolean nullable) throws IOException { super(columnId, schema, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Datum datum) throws IOException { super.write(datum); if (datum != null && datum.isNotNull()) { double val = datum.asFloat8(); indexStatistics.updateDouble(val); if (createBloomFilter) { bloomFilter.addDouble(val); } utils.writeDouble(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2855 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/thirdparty/orc/WriterImpl.java/#L1041-L1082 | 2 | 263 | 2855 | minor |
| 2012 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12754 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2012 | 12754 | critical |
| 827 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7725 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 2 | 827 | 7725 | minor |
| 67 | {"message": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1077 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 2 | 67 | 1077 | minor |
| 1146 | { "message": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 10114 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 1146 | 10114 | critical |
| 326 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 2 | 326 | 3376 | minor |
| 3373 | { "input_code": "public class User {\n private String name;\n private int age;\n\n public User(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n}", "detected_bad_smells": "YES I found bad smells\nthe bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | yes i found bad smellsthe bad smells are: 1. data class | t | t | f | yes i found bad smellsthe bad smells are: 1. data class | blob | 0 | 6419 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 1 | 3373 | 6419 | major |
| 1735 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KafkaTestServer { public static final int CACHE_TTL_MS = 1; private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestServer.class); private int kafkaPort = -1; private TestingServer zkServer; private KafkaServerStartable kafkaServer = null; private File sentrySitePath = null; public KafkaTestServer(File sentrySitePath) throws Exception { this.sentrySitePath = sentrySitePath; createZkServer(); this.kafkaPort = TestUtils.getFreePort(); createKafkaServer(); } public void start() throws Exception { kafkaServer.startup(); LOGGER.info("Started Kafka broker."); } public void shutdown() { if (kafkaServer != null) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); LOGGER.info("Stopped Kafka server."); } if (zkServer != null) { try { zkServer.stop(); LOGGER.info("Stopped ZK server."); } catch (IOException e) { LOGGER.error("Failed to shutdown ZK server.", e); } } } private Path getTempDirectory() { Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory("kafka-sentry-"); } catch (IOException e) { LOGGER.error("Failed to create temp dir for Kafka's log dir."); throw new RuntimeException(e); } return tempDirectory; } private void setupKafkaProps(Properties props) throws UnknownHostException { props.put("listeners", "SSL://" + InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort); props.put("log.dir", getTempDirectory().toAbsolutePath().toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controller.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", true); props.put("delete.topic.enable", false); props.put("controlled.shutdown.retry.backoff.ms", "100"); props.put("port", kafkaPort); props.put("offsets.topic.replication.factor", "1"); props.put("authorizer.class.name", "org.apache.sentry.kafka.authorizer.SentryKafkaAuthorizer"); props.put("sentry.kafka.site.url", "file://" + sentrySitePath.getAbsolutePath()); props.put("allow.everyone.if.no.acl.found", "true"); props.put("ssl.keystore.location", KafkaTestServer.class.getResource("/test.keystore.jks").getPath()); props.put("ssl.keystore.password", "test-ks-passwd"); props.put("ssl.key.password", "test-key-passwd"); props.put("ssl.truststore.location", KafkaTestServer.class.getResource("/test.truststore.jks").getPath()); props.put("ssl.truststore.password", "test-ts-passwd"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); props.put(KafkaAuthConf.KAFKA_SUPER_USERS, "User:CN=superuser;User:CN=superuser1; User:CN=Superuser2 "); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_ENABLE_NAME, "true"); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_TTL_MS_NAME, String.valueOf(CACHE_TTL_MS)); } private void createKafkaServer() throws UnknownHostException { Properties props = new Properties(); setupKafkaProps(props); kafkaServer = KafkaServerStartable.fromProps(props); } private void createZkServer() throws Exception { try { zkServer = new TestingServer(); } catch (Exception e) { LOGGER.error("Failed to create testing zookeeper server."); throw new RuntimeException(e); } } public String getBootstrapServers() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort; } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 11825 | https://github.com/apache/sentry/blob/f859446b65bbc274bc4899464892151eec8217c6/sentry-tests/sentry-tests-kafka/src/main/java/org/apache/sentry/tests/e2e/kafka/KafkaTestServer.java/#L35-L129 | 1 | 1735 | 11825 | minor |
| 784 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 7494 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 784 | 7494 | minor |
| 82 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean visitObjectReference(final Pointer objRef, boolean compressed) { return visitObjectReferenceInline(objRef, 0, compressed); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1195 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.core.genscavenge/src/com/oracle/svm/core/genscavenge/GreyToBlackObjRefVisitor.java/#L61-L64 | 1 | 82 | 1195 | minor |
| 380 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 3907 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 380 | 3907 | major |
| 1977 | YES I found bad smells: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
blob | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | blob | 0 | 12630 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 1977 | 12630 | minor |
| 2061 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12970 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 2061 | 12970 | major |
| 2484 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14604 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 2484 | 14604 | minor |
| 2243 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13626 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 2243 | 13626 | major |
| 431 | { "response": "YES, I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public byte getByteAt(long index) { return addr.getJByteAt(baseOffset + index); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4279 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/Symbol.java/#L77-L79 | 1 | 431 | 4279 | minor |
| 65 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1073 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 2 | 65 | 1073 | minor |
| 1263 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10524 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1263 | 10524 | minor |
| 501 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5079 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 501 | 5079 | major |
| 42 | { "error": "Please provide a code snippet for analysis." } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
feature envy | Not specified | f | f | f | false | 0 | 805 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 42 | 805 | major | |
| 2674 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15226 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2674 | 15226 | minor |
| 37 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObserveUtil { /* keys used to populate the request context */ public static final String CTX_ENDPOINT = "leshan-endpoint"; public static final String CTX_REGID = "leshan-regId"; public static final String CTX_LWM2M_PATH = "leshan-path"; /** * Create a LWM2M observation from a CoAP request. */ public static Observation createLwM2mObservation(Request request) { String regId = null; String lwm2mPath = null; Map context = null; for (Entry ctx : request.getUserContext().entrySet()) { switch (ctx.getKey()) { case CTX_REGID: regId = ctx.getValue(); break; case CTX_LWM2M_PATH: lwm2mPath = ctx.getValue(); break; case CTX_ENDPOINT: break; default: if (context == null) { context = new HashMap<>(); } context.put(ctx.getKey(), ctx.getValue()); } } ContentFormat contentFormat = null; if (request.getOptions().hasAccept()) { contentFormat = ContentFormat.fromCode(request.getOptions().getAccept()); } return new Observation(request.getToken().getBytes(), regId, new LwM2mPath(lwm2mPath), contentFormat, context); } /** * Create a CoAP observe request context with specific keys needed for internal Leshan working. */ public static Map createCoapObserveRequestContext(String endpoint, String registrationId, ObserveRequest request) { Map context = new HashMap<>(); context.put(CTX_ENDPOINT, endpoint); context.put(CTX_REGID, registrationId); context.put(CTX_LWM2M_PATH, request.getPath().toString()); for (Entry ctx : request.getContext().entrySet()) { context.put(ctx.getKey(), ctx.getValue()); } return context; } public static String extractRegistrationId(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_REGID); } public static String extractLwm2mPath(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_LWM2M_PATH); } public static String extractEndpoint(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_ENDPOINT); } /** * Validate the Californium observation. It is valid if it contains all necessary context for Leshan. */ public static String validateCoapObservation(org.eclipse.californium.core.observe.Observation observation) { if (!observation.getRequest().getUserContext().containsKey(CTX_REGID)) throw new IllegalStateException("missing registrationId info in the request context"); if (!observation.getRequest().getUserContext().containsKey(CTX_LWM2M_PATH)) throw new IllegalStateException("missing lwm2m path info in the request context"); String endpoint = observation.getRequest().getUserContext().get(CTX_ENDPOINT); if (endpoint == null) throw new IllegalStateException("missing endpoint info in the request context"); return endpoint; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 758 | https://github.com/eclipse/leshan/blob/eb75fc8b7d5560944e6d532f1a09d5e5c6e54559/leshan-server-cf/src/main/java/org/eclipse/leshan/server/californium/ObserveUtil.java/#L32-L114 | 1 | 37 | 758 | minor |
| 2615 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 15047 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 2615 | 15047 | minor |
| 930 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8354 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 1 | 930 | 8354 | minor |
| 594 | {"message": "YES, I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class DirectExecutorService implements ExecutorService { static final DirectExecutorService INSTANCE = new DirectExecutorService(); private boolean isShutdown = false; @Override public void shutdown() { isShutdown = true; } @Override @Nonnull public List shutdownNow() { isShutdown = true; return Collections.emptyList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isShutdown; } @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) { return isShutdown; } @Override @Nonnull public Future submit(@Nonnull Callable task) { try { T result = task.call(); return new CompletedFuture<>(result, null); } catch (Exception e) { return new CompletedFuture<>(null, e); } } @Override @Nonnull public Future submit(@Nonnull Runnable task, T result) { task.run(); return new CompletedFuture<>(result, null); } @Override @Nonnull public Future submit(@Nonnull Runnable task) { task.run(); return new CompletedFuture<>(null, null); } @Override @Nonnull public List> invokeAll(@Nonnull Collection> tasks) { ArrayList> result = new ArrayList<>(); for (Callable task : tasks) { try { result.add(new CompletedFuture<>(task.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } return result; } @Override @Nonnull public List> invokeAll( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); Iterator> iterator = tasks.iterator(); ArrayList> result = new ArrayList<>(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { result.add(new CompletedFuture<>(callable.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } while (iterator.hasNext()) { iterator.next(); result.add(new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean isDone() { return false; } @Override public T get() { throw new CancellationException("Task has been cancelled."); } @Override public T get(long timeout, @Nonnull TimeUnit unit) { throw new CancellationException("Task has been cancelled."); } }); } return result; } @Override @Nonnull public T invokeAny(@Nonnull Collection> tasks) throws ExecutionException { Exception exception = null; for (Callable task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); } @Override public T invokeAny( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis(timeout); Exception exception = null; Iterator> iterator = tasks.iterator(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { return callable.call(); } catch (Exception e) { // ignore exception and try next exception = e; } } if (iterator.hasNext()) { throw new TimeoutException("Could not finish execution of tasks within time."); } else { throw new ExecutionException("No tasks finished successfully.", exception); } } @Override public void execute(@Nonnull Runnable command) { command.run(); } static class CompletedFuture implements Future { private final V value; private final Exception exception; CompletedFuture(V value, Exception exception) { this.value = value; this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public V get() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } else { return value; } } @Override public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException { return get(); } } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 5924 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/DirectExecutorService.java/#L37-L252 | 1 | 594 | 5924 | minor |
| 1049 | { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 9463 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1049 | 9463 | minor |
| 2267 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 13734 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 2267 | 13734 | critical |
| 37 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObserveUtil { /* keys used to populate the request context */ public static final String CTX_ENDPOINT = "leshan-endpoint"; public static final String CTX_REGID = "leshan-regId"; public static final String CTX_LWM2M_PATH = "leshan-path"; /** * Create a LWM2M observation from a CoAP request. */ public static Observation createLwM2mObservation(Request request) { String regId = null; String lwm2mPath = null; Map context = null; for (Entry ctx : request.getUserContext().entrySet()) { switch (ctx.getKey()) { case CTX_REGID: regId = ctx.getValue(); break; case CTX_LWM2M_PATH: lwm2mPath = ctx.getValue(); break; case CTX_ENDPOINT: break; default: if (context == null) { context = new HashMap<>(); } context.put(ctx.getKey(), ctx.getValue()); } } ContentFormat contentFormat = null; if (request.getOptions().hasAccept()) { contentFormat = ContentFormat.fromCode(request.getOptions().getAccept()); } return new Observation(request.getToken().getBytes(), regId, new LwM2mPath(lwm2mPath), contentFormat, context); } /** * Create a CoAP observe request context with specific keys needed for internal Leshan working. */ public static Map createCoapObserveRequestContext(String endpoint, String registrationId, ObserveRequest request) { Map context = new HashMap<>(); context.put(CTX_ENDPOINT, endpoint); context.put(CTX_REGID, registrationId); context.put(CTX_LWM2M_PATH, request.getPath().toString()); for (Entry ctx : request.getContext().entrySet()) { context.put(ctx.getKey(), ctx.getValue()); } return context; } public static String extractRegistrationId(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_REGID); } public static String extractLwm2mPath(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_LWM2M_PATH); } public static String extractEndpoint(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_ENDPOINT); } /** * Validate the Californium observation. It is valid if it contains all necessary context for Leshan. */ public static String validateCoapObservation(org.eclipse.californium.core.observe.Observation observation) { if (!observation.getRequest().getUserContext().containsKey(CTX_REGID)) throw new IllegalStateException("missing registrationId info in the request context"); if (!observation.getRequest().getUserContext().containsKey(CTX_LWM2M_PATH)) throw new IllegalStateException("missing lwm2m path info in the request context"); String endpoint = observation.getRequest().getUserContext().get(CTX_ENDPOINT); if (endpoint == null) throw new IllegalStateException("missing endpoint info in the request context"); return endpoint; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 758 | https://github.com/eclipse/leshan/blob/eb75fc8b7d5560944e6d532f1a09d5e5c6e54559/leshan-server-cf/src/main/java/org/eclipse/leshan/server/californium/ObserveUtil.java/#L32-L114 | 2 | 37 | 758 | minor |
| 1751 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 11859 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 1 | 1751 | 11859 | minor |
| 1706 | {"message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 11754 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 2 | 1706 | 11754 | critical |
| 608 | YES I found bad smells the bad smells are: 1. Lack of indentation 2. Code duplication within the constructors 3. Inconsistent naming conventions (e.g. "reference" vs "newValue") 4. Lack of comments/documentation 5. Lack of error handling for the "set" method 6. Lack of validation for the "set" method parameters 7. Tight coupling between the ReferenceProperty and EntityReference classes 8. Inappropriate use of the interface, as there is only one implementation of it | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | Lack of indentation2 Code duplication within the constructors3 Inconsistent naming conventions (eg "reference" vs "newValue")4 Lack of comments/documentation5 Lack of error handling for the "set" method6 Lack of validation for the "set" method parameters 7 Tight coupling between the ReferenceProperty and EntityReference classes 8 Inappropriate use of the interface, as there is only one implementation of it | t | f | f | . Lack of indentation2. Code duplication within the constructors3. Inconsistent naming conventions (e.g. "reference" vs "newValue")4. Lack of comments/documentation5. Lack of error handling for the "set" method6. Lack of validation for the "set" method parameters 7. Tight coupling between the ReferenceProperty and EntityReference classes 8. Inappropriate use of the interface, as there is only one implementation of it | data class | 0 | 6114 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 2 | 608 | 6114 | major |
| 55 | { "response": "NO, I did not find any bad smell" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 959 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 2 | 55 | 959 | minor | ||
| 833 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 7743 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 1 | 833 | 7743 | minor |
| 2759 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private BundleEvent initializeEvent(Bundle bundle) { switch (bundle.getState()) { case Bundle.INSTALLED: return new BundleEvent(BundleEvent.INSTALLED, bundle); case Bundle.RESOLVED: return new BundleEvent(BundleEvent.RESOLVED, bundle); default: return new BundleEvent(BundleEvent.STARTED, bundle); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 874 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.providers/src/main/java/org/eclipse/smarthome/automation/internal/core/provider/AutomationResourceBundlesTracker.java/#L278-L287 | 1 | 2759 | 874 | minor |
| 1614 | {"message": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
feature envy | t | f | f | feature envy | 0 | 11471 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 1614 | 11471 | minor | ||
| 226 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @HaHotStateRequired public class SensorResource extends AbstractBrooklynRestResource implements SensorApi { private static final Logger log = LoggerFactory.getLogger(SensorResource.class); @Override public List list(final String application, final String entityToken) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } List result = Lists.newArrayList(); for (AttributeSensor sensor : filter(entity.getEntityType().getSensors(), AttributeSensor.class)) { // Exclude config that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from AttributeSensor list results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } result.add(SensorTransformer.sensorSummary(entity, sensor, ui.getBaseUriBuilder())); } return result; } @Override public Map batchSensorRead(final String application, final String entityToken, final Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } Map sensorMap = Maps.newHashMap(); @SuppressWarnings("rawtypes") Iterable sensors = filter(entity.getEntityType().getSensors(), AttributeSensor.class); for (AttributeSensor sensor : sensors) { // Exclude sensors that user is not allowed to see if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { log.trace("User {} not authorized to see sensor {} of entity {}; excluding from current-state results", new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity}); continue; } Object value = entity.getAttribute(findSensor(entity, sensor.getName())); sensorMap.put(sensor.getName(), resolving(value).preferJson(true).asJerseyOutermostReturnValue(false).raw(raw).context(entity).timeout(Duration.ZERO).renderAs(sensor).resolve()); } return sensorMap; } protected Object get(boolean preferJson, String application, String entityToken, String sensorName, Boolean raw) { final Entity entity = brooklyn().getEntity(application, entityToken); AttributeSensor sensor = findSensor(entity, sensorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem(entity, sensor.getName()))) { throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s' sensor '%s'", Entitlements.getEntitlementContext().user(), entity, sensor.getName()); } Object value = entity.getAttribute(sensor); return resolving(value).preferJson(preferJson).asJerseyOutermostReturnValue(true).raw(raw).context(entity).immediately(true).renderAs(sensor).resolve(); } @Override public String getPlain(String application, String entityToken, String sensorName, final Boolean raw) { return (String) get(false, application, entityToken, sensorName, raw); } @Override public Object get(final String application, final String entityToken, String sensorName, final Boolean raw) { return get(true, application, entityToken, sensorName, raw); } private AttributeSensor findSensor(Entity entity, String name) { Sensor s = entity.getEntityType().getSensor(name); if (s instanceof AttributeSensor) return (AttributeSensor) s; return new BasicAttributeSensor(Object.class, name); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void setFromMap(String application, String entityToken, Map newValues) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensors "+newValues); for (Object entry: newValues.entrySet()) { String sensorName = Strings.toString(((Map.Entry)entry).getKey()); Object newValue = ((Map.Entry)entry).getValue(); AttributeSensor sensor = findSensor(entity, sensorName); entity.sensors().set(sensor, newValue); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void set(String application, String entityToken, String sensorName, Object newValue) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensor "+sensorName+" to "+newValue); entity.sensors().set(sensor, newValue); } @Override public void delete(String application, String entityToken, String sensorName) { final Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } AttributeSensor sensor = findSensor(entity, sensorName); if (log.isDebugEnabled()) log.debug("REST user "+Entitlements.getEntitlementContext()+" deleting sensor "+sensorName); ((EntityInternal)entity).sensors().remove(sensor); } } |
blob | long method | t | t | f | long method | blob | 0 | 2447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/SensorResource.java/#L46-L183 | 1 | 226 | 2447 | major |
| 3923 | YES, I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 10270 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 3923 | 10270 | minor |
| 2570 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | blob | t | t | f | blob | data class | 0 | 14881 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 2570 | 14881 | minor |
| 1116 | YES I found bad smells the bad smells are: 1. Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH) 2. Long method (toString()) 3. Shotgun surgery (changing and setting multiple variables in different methods) 4. Magic numbers (arbitrary values like -1, 10) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH)2 Long method (toString())3 Shotgun surgery (changing and setting multiple variables in different methods)4 Magic numbers (arbitrary values like - | t | f | f | . Duplicated code (DEFAULT_MAX_RETRIES_ON_DELETE, DEFAULT_MAX_RETRIES_ON_TOUCH)2. Long method (toString())3. Shotgun surgery (changing and setting multiple variables in different methods)4. Magic numbers (arbitrary values like - | data class | 0 | 9954 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 2 | 1116 | 9954 | major |
| 2796 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | f | f | f | data class | 0 | 1230 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 2 | 2796 | 1230 | minor | ||
| 3565 | { "message": "YES I found bad smells", "the bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExplainTask extends Task implements Serializable { public static final String STAGE_DEPENDENCIES = "STAGE DEPENDENCIES"; private static final long serialVersionUID = 1L; public static final String EXPL_COLUMN_NAME = "Explain"; private final Set> visitedOps = new HashSet>(); private boolean isLogical = false; protected final Logger LOG; public ExplainTask() { super(); LOG = LoggerFactory.getLogger(this.getClass().getName()); } /* * Below method returns the dependencies for the passed in query to EXPLAIN. * The dependencies are the set of input tables and partitions, and are * provided back as JSON output for the EXPLAIN command. * Example output: * {"input_tables":[{"tablename": "default@test_sambavi_v1", "tabletype": "TABLE"}], * "input partitions":["default@srcpart@ds=2008-04-08/hr=11"]} */ @VisibleForTesting static JSONObject getJSONDependencies(ExplainWork work) throws Exception { assert(work.getDependency()); JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); JSONArray inputTableInfo = new JSONArray(); JSONArray inputPartitionInfo = new JSONArray(); for (ReadEntity input: work.getInputs()) { switch (input.getType()) { case TABLE: Table table = input.getTable(); JSONObject tableInfo = new JSONObject(); tableInfo.put("tablename", table.getCompleteName()); tableInfo.put("tabletype", table.getTableType().toString()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { tableInfo.put("tableParents", input.getParents().toString()); } inputTableInfo.put(tableInfo); break; case PARTITION: JSONObject partitionInfo = new JSONObject(); partitionInfo.put("partitionName", input.getPartition().getCompleteName()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { partitionInfo.put("partitionParents", input.getParents().toString()); } inputPartitionInfo.put(partitionInfo); break; default: break; } } outJSONObject.put("input_tables", inputTableInfo); outJSONObject.put("input_partitions", inputPartitionInfo); return outJSONObject; } public JSONObject getJSONCBOPlan(PrintStream out, ExplainWork work) throws Exception { JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); String cboPlan = work.getCboPlan(); if (cboPlan != null) { if (jsonOutput) { outJSONObject.put("CBOPlan", cboPlan); } else { out.println("CBO PLAN:"); out.println(cboPlan); } } return outJSONObject; } public JSONObject getJSONLogicalPlan(PrintStream out, ExplainWork work) throws Exception { isLogical = true; JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } if (work.getParseContext() != null) { if (out != null) { out.print("LOGICAL PLAN:"); } JSONObject jsonPlan = outputMap(work.getParseContext().getTopOps(), true, out, work.getExtended(), jsonOutput, 0); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("LOGICAL PLAN", jsonPlan); } } else { System.err.println("No parse context!"); } return outJSONObject; } private static String trueCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS true"; private static String falseCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS false"; @VisibleForTesting ImmutablePair outputPlanVectorization(PrintStream out, boolean jsonOutput) throws Exception { if (out != null) { out.println("PLAN VECTORIZATION:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; HiveConf hiveConf = queryState.getConf(); boolean isVectorizationEnabled = HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED); String isVectorizationEnabledCondName = (isVectorizationEnabled ? trueCondNameVectorizationEnabled : falseCondNameVectorizationEnabled); List isVectorizationEnabledCondList = Arrays.asList(isVectorizationEnabledCondName); if (out != null) { out.print(indentString(2)); out.print("enabled: "); out.println(isVectorizationEnabled); out.print(indentString(2)); if (!isVectorizationEnabled) { out.print("enabledConditionsNotMet: "); } else { out.print("enabledConditionsMet: "); } out.println(isVectorizationEnabledCondList); } if (jsonOutput) { json.put("enabled", isVectorizationEnabled); JSONArray jsonArray = new JSONArray(Arrays.asList(isVectorizationEnabledCondName)); if (!isVectorizationEnabled) { json.put("enabledConditionsNotMet", jsonArray); } else { json.put("enabledConditionsMet", jsonArray); } } return new ImmutablePair(isVectorizationEnabled, jsonOutput ? json : null); } public JSONObject getJSONPlan(PrintStream out, ExplainWork work) throws Exception { return getJSONPlan(out, work.getRootTasks(), work.getFetchTask(), work.isFormatted(), work.getExtended(), work.isAppendTaskType(), work.getCboInfo(), work.getOptimizedSQL()); } public JSONObject getJSONPlan(PrintStream out, List> tasks, Task fetchTask, boolean jsonOutput, boolean isExtended, boolean appendTaskType, String cboInfo, String optimizedSQL) throws Exception { // If the user asked for a formatted output, dump the json output // in the output stream JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); if (jsonOutput) { out = null; } if (optimizedSQL != null) { if (jsonOutput) { outJSONObject.put("optimizedSQL", optimizedSQL); } else { out.print("OPTIMIZED SQL: "); out.println(optimizedSQL); } } List ordered = StageIDsRearranger.getExplainOrder(conf, tasks); if (fetchTask != null) { fetchTask.setParentTasks((List)StageIDsRearranger.getFetchSources(tasks)); if (fetchTask.getNumParent() == 0) { fetchTask.setRootTask(true); } ordered.add(fetchTask); } boolean suppressOthersForVectorization = false; if (this.work != null && this.work.isVectorization()) { ImmutablePair planVecPair = outputPlanVectorization(out, jsonOutput); if (this.work.isVectorizationOnly()) { // Suppress the STAGES if vectorization is off. suppressOthersForVectorization = !planVecPair.left; } if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("PLAN VECTORIZATION", planVecPair.right); } } if (!suppressOthersForVectorization) { JSONObject jsonDependencies = outputDependencies(out, jsonOutput, appendTaskType, ordered); if (out != null) { out.println(); } if (jsonOutput) { if (cboInfo != null) { outJSONObject.put("cboInfo", cboInfo); } outJSONObject.put(STAGE_DEPENDENCIES, jsonDependencies); } // Go over all the tasks and dump out the plans JSONObject jsonPlan = outputStagePlans(out, ordered, jsonOutput, isExtended); if (jsonOutput) { outJSONObject.put("STAGE PLANS", jsonPlan); } if (fetchTask != null) { fetchTask.setParentTasks(null); } } return jsonOutput ? outJSONObject : null; } private List toString(Collection objects) { List list = new ArrayList(); for (Object object : objects) { list.add(String.valueOf(object)); } return list; } private Object toJson(String header, String message, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return message; } out.print(header); out.println(": "); out.print(indentString(2)); out.println(message); return null; } private Object toJson(String header, List messages, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return new JSONArray(messages); } out.print(header); out.println(": "); for (String message : messages) { out.print(indentString(2)); out.print(message); out.println(); } return null; } private JSONObject getLocks(PrintStream out, ExplainWork work) { JSONObject jsonObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } List lockComponents = AcidUtils.makeLockComponents(work.getOutputs(), work.getInputs(), conf); if (null != out) { out.print("LOCK INFORMATION:\n"); } List locks = new ArrayList<>(lockComponents.size()); for (LockComponent component : lockComponents) { ExplainLockDesc lockDesc = new ExplainLockDesc(component); if (null != out) { out.print(lockDesc.getFullName()); out.print(" -> "); out.print(lockDesc.getLockType()); out.print('\n'); } else { locks.add(lockDesc); } } if (jsonOutput) { jsonObject.put("LOCK INFORMATION:", locks); } return jsonObject; } @Override public int execute(DriverContext driverContext) { PrintStream out = null; try { Path resFile = work.getResFile(); OutputStream outS = resFile.getFileSystem(conf).create(resFile); out = new PrintStream(outS); if (work.isCbo()) { JSONObject jsonCBOPlan = getJSONCBOPlan(out, work); if (work.isFormatted()) { out.print(jsonCBOPlan); } } else if (work.isLogical()) { JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work); if (work.isFormatted()) { out.print(jsonLogicalPlan); } } else if (work.isAuthorize()) { JSONObject jsonAuth = collectAuthRelatedEntities(out, work); if (work.isFormatted()) { out.print(jsonAuth); } } else if (work.getDependency()) { JSONObject jsonDependencies = getJSONDependencies(work); out.print(jsonDependencies); } else if (work.isLocks()) { JSONObject jsonLocks = getLocks(out, work); if(work.isFormatted()) { out.print(jsonLocks); } } else if (work.isAst()) { // Print out the parse AST if (work.getAstStringTree() != null) { outputAST(work.getAstStringTree(), out, work.isFormatted(), 0); } } else { if (work.isUserLevelExplain()) { // Because of the implementation of the JsonParserFactory, we are sure // that we can get a TezJsonParser. JsonParser jsonParser = JsonParserFactory.getParser(conf); work.getConfig().setFormatted(true); JSONObject jsonPlan = getJSONPlan(out, work); if (work.getCboInfo() != null) { jsonPlan.put("cboInfo", work.getCboInfo()); } try { jsonParser.print(jsonPlan, out); } catch (Exception e) { // if there is anything wrong happen, we bail out. LOG.error("Running explain user level has problem." + " Falling back to normal explain.", e); work.getConfig().setFormatted(false); work.getConfig().setUserLevelExplain(false); jsonPlan = getJSONPlan(out, work); } } else { JSONObject jsonPlan = getJSONPlan(out, work); if (work.isFormatted()) { // use the parser to get the output operators of RS JsonParser jsonParser = JsonParserFactory.getParser(conf); if (jsonParser != null) { jsonParser.print(jsonPlan, null); LOG.info("JsonPlan is augmented to {}", jsonPlan); } out.print(jsonPlan); } } } out.close(); out = null; return (0); } catch (Exception e) { LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e)); setException(e); return (1); } finally { IOUtils.closeStream(out); } } @VisibleForTesting JSONObject collectAuthRelatedEntities(PrintStream out, ExplainWork work) throws Exception { BaseSemanticAnalyzer analyzer = work.getAnalyzer(); HiveOperation operation = queryState.getHiveOperation(); JSONObject object = new JSONObject(new LinkedHashMap<>()); Object jsonInput = toJson("INPUTS", toString(analyzer.getInputs()), out, work); if (work.isFormatted()) { object.put("INPUTS", jsonInput); } Object jsonOutput = toJson("OUTPUTS", toString(analyzer.getOutputs()), out, work); if (work.isFormatted()) { object.put("OUTPUTS", jsonOutput); } String userName = SessionState.get().getAuthenticator().getUserName(); Object jsonUser = toJson("CURRENT_USER", userName, out, work); if (work.isFormatted()) { object.put("CURRENT_USER", jsonUser); } Object jsonOperation = toJson("OPERATION", operation.name(), out, work); if (work.isFormatted()) { object.put("OPERATION", jsonOperation); } if (analyzer.skipAuthorization()) { return object; } final List exceptions = new ArrayList(); Object delegate = SessionState.get().getActiveAuthorizer(); if (delegate != null) { Class itface = SessionState.get().getAuthorizerInterface(); Object authorizer = AuthorizationFactory.create(delegate, itface, new AuthorizationFactory.AuthorizationExceptionHandler() { @Override public void exception(Exception exception) { exceptions.add(exception.getMessage()); } }); SessionState.get().setActiveAuthorizer(authorizer); try { Driver.doAuthorization(queryState.getHiveOperation(), analyzer, ""); } finally { SessionState.get().setActiveAuthorizer(delegate); } } if (!exceptions.isEmpty()) { Object jsonFails = toJson("AUTHORIZATION_FAILURES", exceptions, out, work); if (work.isFormatted()) { object.put("AUTHORIZATION_FAILURES", jsonFails); } } return object; } private static String indentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.append(" "); } return sb.toString(); } @VisibleForTesting JSONObject outputMap(Map mp, boolean hasHeader, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { TreeMap tree = getBasictypeKeyedMap(mp); JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null && hasHeader && !mp.isEmpty()) { out.println(); } for (Entry ent : tree.entrySet()) { // Print the key if (out != null) { out.print(indentString(indent)); out.print(ent.getKey()); out.print(" "); } // Print the value if (isPrintable(ent.getValue())) { if (out != null) { out.print(ent.getValue()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() instanceof List) { if (ent.getValue() != null && !((List)ent.getValue()).isEmpty() && ((List)ent.getValue()).get(0) != null && ((List)ent.getValue()).get(0) instanceof TezWork.Dependency) { if (out != null) { boolean isFirst = true; for (TezWork.Dependency dep: (List)ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getType()); out.print(")"); } out.println(); } if (jsonOutput) { for (TezWork.Dependency dep: (List)ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getType()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else if (ent.getValue() != null && !((List) ent.getValue()).isEmpty() && ((List) ent.getValue()).get(0) != null && ((List) ent.getValue()).get(0) instanceof SparkWork.Dependency) { if (out != null) { boolean isFirst = true; for (SparkWork.Dependency dep: (List) ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getShuffleType()); out.print(", "); out.print(dep.getNumPartitions()); out.print(")"); } out.println(); } if (jsonOutput) { for (SparkWork.Dependency dep: (List) ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getShuffleType()); jsonDep.put("partitions", dep.getNumPartitions()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } } else if (ent.getValue() instanceof Map) { String stringValue = getBasictypeKeyedMap((Map)ent.getValue()).toString(); if (out != null) { out.print(stringValue); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), stringValue); } } else if (ent.getValue() != null) { if (out != null) { out.println(); } JSONObject jsonOut = outputPlan(ent.getValue(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (jsonOutput) { json.put(ent.getKey().toString(), jsonOut); } } else { if (out != null) { out.println(); } } } return jsonOutput ? json : null; } /** * Retruns a map which have either primitive or string keys. * * This is neccessary to discard object level comparators which may sort the objects based on some non-trivial logic. * * @param mp * @return */ private TreeMap getBasictypeKeyedMap(Map mp) { TreeMap ret = new TreeMap(); if (mp.size() > 0) { Object firstKey = mp.keySet().iterator().next(); if (firstKey.getClass().isPrimitive() || firstKey instanceof String) { // keep it as-is ret.putAll(mp); return ret; } else { for (Entry entry : mp.entrySet()) { // discard possibly type related sorting order and replace with alphabetical ret.put(entry.getKey().toString(), entry.getValue()); } } } return ret; } private JSONArray outputList(List l, PrintStream out, boolean hasHeader, boolean extended, boolean jsonOutput, int indent, boolean inTest) throws Exception { boolean first_el = true; boolean nl = false; JSONArray outputArray = new JSONArray(); for (Object o : l) { if (isPrintable(o)) { String delim = first_el ? " " : ", "; if (out != null) { out.print(delim); out.print(o); } if (jsonOutput) { outputArray.put(o); } nl = true; } else { if (first_el && (out != null) && hasHeader) { out.println(); } JSONObject jsonOut = outputPlan(o, out, extended, jsonOutput, jsonOutput ? 0 : (hasHeader ? indent + 2 : indent), "", inTest); if (jsonOutput) { outputArray.put(jsonOut); } } first_el = false; } if (nl && (out != null)) { out.println(); } return jsonOutput ? outputArray : null; } private boolean isPrintable(Object val) { if (val instanceof Boolean || val instanceof String || val instanceof Integer || val instanceof Long || val instanceof Byte || val instanceof Float || val instanceof Double || val instanceof Path) { return true; } if (val != null && val.getClass().isPrimitive()) { return true; } return false; } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, ""); } private boolean isInvokeVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // The EXPLAIN VECTORIZATION option was specified. final boolean desireOnly = this.work.isVectorizationOnly(); final VectorizationDetailLevel desiredVecDetailLevel = this.work.isVectorizationDetailLevel(); switch (vectorization) { case NON_VECTORIZED: // Display all non-vectorized leaf objects unless ONLY. if (desireOnly) { invokeFlag = false; } break; case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: if (vectorization.rank < desiredVecDetailLevel.rank) { // This detail not desired. invokeFlag = false; } break; case SUMMARY_PATH: case OPERATOR_PATH: if (desireOnly) { if (vectorization.rank < desiredVecDetailLevel.rank) { // Suppress headers and all objects below. invokeFlag = false; } } break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } private boolean isInvokeNonVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // Do not display vectorization objects. switch (vectorization) { case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: invokeFlag = false; break; case NON_VECTORIZED: // No action. break; case SUMMARY_PATH: case OPERATOR_PATH: // Always include headers since they contain non-vectorized objects, too. break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } @VisibleForTesting JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, appendToHeader, queryState.getConf().getBoolVar(ConfVars.HIVE_IN_TEST)); } public JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader, boolean inTest) throws Exception { // Check if work has an explain annotation Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class); String keyJSONObject = null; if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } if (invokeFlag) { keyJSONObject = xpl_note.displayName(); if (out != null) { out.print(indentString(indent)); if (appendToHeader != null && !appendToHeader.isEmpty()) { out.println(xpl_note.displayName() + appendToHeader); } else { out.println(xpl_note.displayName()); } } } } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; // If this is an operator then we need to call the plan generation on the // conf and then the children if (work instanceof Operator) { Operator operator = (Operator) work; if (operator.getConf() != null) { String appender = isLogical ? " (" + operator.getOperatorId() + ")" : ""; JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput, jsonOutput ? 0 : indent, appender, inTest); if (this.work != null && (this.work.isUserLevelExplain() || this.work.isFormatted())) { if (jsonOut != null && jsonOut.length() > 0) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:", operator.getOperatorId()); } if (!this.work.isUserLevelExplain() && this.work.isFormatted() && operator.getConf() instanceof ReduceSinkDesc ) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("outputname:", ((ReduceSinkDesc) operator.getConf()).getOutputName()); } } if (jsonOutput) { json = jsonOut; } } if (!visitedOps.contains(operator) || !isLogical) { visitedOps.add(operator); if (operator.getChildOperators() != null) { int cindent = jsonOutput ? 0 : indent + 2; for (Operator op : operator.getChildOperators()) { JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent, "", inTest); if (jsonOutput) { ((JSONObject)json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut); } } } } if (jsonOutput) { return json; } return null; } // We look at all methods that generate values for explain Method[] methods = work.getClass().getMethods(); Arrays.sort(methods, new MethodComparator()); for (Method m : methods) { int prop_indents = jsonOutput ? 0 : indent + 2; note = AnnotationUtils.getAnnotation(m, Explain.class); if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (invokeFlag) { if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } } if (invokeFlag) { Object val = null; try { if(postProcess(xpl_note)) { val = m.invoke(work, inTest); } else{ val = m.invoke(work); } } catch (InvocationTargetException ex) { // Ignore the exception, this may be caused by external jars val = null; } if (val == null) { continue; } if(xpl_note.jsonOnly() && !jsonOutput) { continue; } String header = null; boolean skipHeader = xpl_note.skipHeader(); boolean emptyHeader = false; if (!xpl_note.displayName().equals("")) { header = indentString(prop_indents) + xpl_note.displayName() + ":"; } else { emptyHeader = true; prop_indents = indent; header = indentString(prop_indents); } // Try the output as a primitive object if (isPrintable(val)) { if (out != null && shouldPrint(xpl_note, val)) { if (!skipHeader) { out.print(header); out.print(" "); } out.println(val); } if (jsonOutput && shouldPrint(xpl_note, val)) { json.put(header, val.toString()); } continue; } int ind = 0; if (!jsonOutput) { if (!skipHeader) { ind = prop_indents + 2; } else { ind = indent; } } // Try this as a map if (val instanceof Map) { // Go through the map and print out the stuff Map mp = (Map) val; if (out != null && !skipHeader && mp != null && !mp.isEmpty()) { out.print(header); } JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput, ind); if (jsonOutput && !mp.isEmpty()) { json.put(header, jsonOut); } continue; } // Try this as a list if (val instanceof List || val instanceof Set) { List l = val instanceof List ? (List)val : new ArrayList((Set)val); if (out != null && !skipHeader && l != null && !l.isEmpty()) { out.print(header); } JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput, ind, inTest); if (jsonOutput && !l.isEmpty()) { json.put(header, jsonOut); } continue; } // Finally check if it is serializable try { if (!skipHeader && out != null) { out.println(header); } JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind, "", inTest); if (jsonOutput && jsonOut != null && jsonOut.length() != 0) { if (!skipHeader) { json.put(header, jsonOut); } else { for(String k: JSONObject.getNames(jsonOut)) { json.put(k, jsonOut.get(k)); } } } continue; } catch (ClassCastException ce) { // Ignore } } } } if (jsonOutput) { if (keyJSONObject != null) { JSONObject ret = new JSONObject(new LinkedHashMap<>()); ret.put(keyJSONObject, json); return ret; } return json; } return null; } /** * use case: this is only use for testing purposes. For instance, we might * want to sort the expressions in a filter so we get deterministic comparable * golden files */ private boolean postProcess(Explain exp) { return exp.postProcess(); } /** * use case: we want to print the object in explain only if it is true * how to do : print it unless the following 3 are all true: * 1. displayOnlyOnTrue tag is on * 2. object is boolean * 3. object is false * @param exp * @param val * @return */ private boolean shouldPrint(Explain exp, Object val) { if (exp.displayOnlyOnTrue() && (val instanceof Boolean) & !((Boolean)val)) { return false; } return true; } private JSONObject outputPlan(Task task, PrintStream out, JSONObject parentJSON, boolean extended, boolean jsonOutput, int indent) throws Exception { if (out != null) { out.print(indentString(indent)); out.print("Stage: "); out.print(task.getId()); out.print("\n"); } // Start by getting the work part of the task and call the output plan for // the work JSONObject jsonOutputPlan = outputPlan(task.getWork(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (out != null) { out.println(); } if (jsonOutput) { parentJSON.put(task.getId(), jsonOutputPlan); } return null; } @VisibleForTesting JSONObject outputDependencies(Task task, PrintStream out, JSONObject parentJson, boolean jsonOutput, boolean taskType, int indent) throws Exception { boolean first = true; JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null) { out.print(indentString(indent)); out.print(task.getId()); } if ((task.getParentTasks() == null || task.getParentTasks().isEmpty())) { if (task.isRootTask()) { if (out != null) { out.print(" is a root stage"); } if (jsonOutput) { json.put("ROOT STAGE", "TRUE"); } } } else { StringBuilder s = new StringBuilder(); first = true; for (Task parent : task.getParentTasks()) { if (!first) { s.append(", "); } first = false; s.append(parent.getId()); } if (out != null) { out.print(" depends on stages: "); out.print(s.toString()); } if (jsonOutput) { json.put("DEPENDENT STAGES", s.toString()); } } Task currBackupTask = task.getBackupTask(); if (currBackupTask != null) { if (out != null) { out.print(" has a backup stage: "); out.print(currBackupTask.getId()); } if (jsonOutput) { json.put("BACKUP STAGE", currBackupTask.getId()); } } if (task instanceof ConditionalTask && ((ConditionalTask) task).getListTasks() != null) { StringBuilder s = new StringBuilder(); first = true; for (Task con : ((ConditionalTask) task).getListTasks()) { if (!first) { s.append(", "); } first = false; s.append(con.getId()); } if (out != null) { out.print(" , consists of "); out.print(s.toString()); } if (jsonOutput) { json.put("CONDITIONAL CHILD TASKS", s.toString()); } } if (taskType) { if (out != null) { out.print(" ["); out.print(task.getType()); out.print("]"); } if (jsonOutput) { json.put("TASK TYPE", task.getType().name()); } } if (out != null) { out.println(); } return jsonOutput ? json : null; } public String outputAST(String treeString, PrintStream out, boolean jsonOutput, int indent) throws JSONException { if (out != null) { out.print(indentString(indent)); out.println("ABSTRACT SYNTAX TREE:"); out.print(indentString(indent + 2)); out.println(treeString); } return jsonOutput ? treeString : null; } public JSONObject outputDependencies(PrintStream out, boolean jsonOutput, boolean appendTaskType, List tasks) throws Exception { if (out != null) { out.println(STAGE_DEPENDENCIES + ":"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { JSONObject jsonOut = outputDependencies(task, out, json, jsonOutput, appendTaskType, 2); if (jsonOutput && jsonOut != null) { json.put(task.getId(), jsonOut); } } return jsonOutput ? json : null; } public JSONObject outputStagePlans(PrintStream out, List tasks, boolean jsonOutput, boolean isExtended) throws Exception { if (out != null) { out.println("STAGE PLANS:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { outputPlan(task, out, json, isExtended, jsonOutput, 2); } return jsonOutput ? json : null; } /** * MethodComparator. * */ public class MethodComparator implements Comparator { @Override public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } } @Override public StageType getType() { return StageType.EXPLAIN; } @Override public String getName() { return "EXPLAIN"; } public static List getResultSchema() { FieldSchema tmpFieldSchema = new FieldSchema(); List colList = new ArrayList(); tmpFieldSchema.setName(EXPL_COLUMN_NAME); tmpFieldSchema.setType(STRING_TYPE_NAME); colList.add(tmpFieldSchema); return colList; } @Override public boolean canExecuteInParallel() { return false; } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 7829 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/ExplainTask.java/#L84-L1302 | 1 | 3565 | 7829 | critical |
| 862 | { "message": "YES I found bad smells.", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExecutorTransfer { private static final Logger LOG = LoggerFactory.getLogger(ExecutorTransfer.class); private final WorkerState workerData; private final KryoTupleSerializer serializer; private final boolean isDebug; private int indexingBase = 0; private ArrayList localReceiveQueues; // [taskId-indexingBase] => queue : List of all recvQs local to this worker private AtomicReferenceArray queuesToFlush; // [taskId-indexingBase] => queue, some entries can be null. : outbound Qs for this executor instance public ExecutorTransfer(WorkerState workerData, Map topoConf) { this.workerData = workerData; this.serializer = new KryoTupleSerializer(topoConf, workerData.getWorkerTopologyContext()); this.isDebug = ObjectReader.getBoolean(topoConf.get(Config.TOPOLOGY_DEBUG), false); } // to be called after all Executor objects in the worker are created and before this object is used public void initLocalRecvQueues() { Integer minTaskId = workerData.getLocalReceiveQueues().keySet().stream().min(Integer::compareTo).get(); this.localReceiveQueues = Utils.convertToArray(workerData.getLocalReceiveQueues(), minTaskId); this.indexingBase = minTaskId; this.queuesToFlush = new AtomicReferenceArray(localReceiveQueues.size()); } // adds addressedTuple to destination Q if it is not full. else adds to pendingEmits (if its not null) public boolean tryTransfer(AddressedTuple addressedTuple, Queue pendingEmits) { if (isDebug) { LOG.info("TRANSFERRING tuple {}", addressedTuple); } JCQueue localQueue = getLocalQueue(addressedTuple); if (localQueue != null) { return tryTransferLocal(addressedTuple, localQueue, pendingEmits); } return workerData.tryTransferRemote(addressedTuple, pendingEmits, serializer); } // flushes local and remote messages public void flush() throws InterruptedException { flushLocal(); workerData.flushRemotes(); } private void flushLocal() throws InterruptedException { for (int i = 0; i < queuesToFlush.length(); i++) { JCQueue q = queuesToFlush.get(i); if (q != null) { q.flush(); queuesToFlush.set(i, null); } } } public JCQueue getLocalQueue(AddressedTuple tuple) { if ((tuple.dest - indexingBase) >= localReceiveQueues.size()) { return null; } return localReceiveQueues.get(tuple.dest - indexingBase); } /** * Adds tuple to localQueue (if overflow is empty). If localQueue is full adds to pendingEmits instead. pendingEmits can be null. * Returns false if unable to add to localQueue. */ public boolean tryTransferLocal(AddressedTuple tuple, JCQueue localQueue, Queue pendingEmits) { workerData.checkSerialize(serializer, tuple); if (pendingEmits != null) { if (pendingEmits.isEmpty() && localQueue.tryPublish(tuple)) { queuesToFlush.set(tuple.dest - indexingBase, localQueue); return true; } else { pendingEmits.add(tuple); return false; } } else { return localQueue.tryPublish(tuple); } } } |
blob | long method | t | t | f | long method | blob | 0 | 7911 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/executor/ExecutorTransfer.java/#L30-L113 | 1 | 862 | 7911 | minor |
| 1521 | { "message": "YES I found bad smells", "detected_bad_smells": { "1. Long Method": {}, "2. Feature Envy": {} } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | t | f | f | feature envy | 0 | 11173 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1521 | 11173 | minor | ||
| 5648 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | f | f | f | long method | 0 | 11201 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5648 | 11201 | major | ||
| 213 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2324 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 1 | 213 | 2324 | minor |
| 1720 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11795 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 1720 | 11795 | minor |
| 777 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7370 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 2 | 777 | 7370 | minor |
| 1953 | YES,I found bad smells. the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | blob | 0 | 12539 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 2 | 1953 | 12539 | critical |
| 515 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | "YES I found bad smells","the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 5310 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 1 | 515 | 5310 | minor |
| 2076 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13050 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 2 | 2076 | 13050 | major |
| 895 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UpdateErrors implements Message { /** */ private static final long serialVersionUID = 0L; /** Failed keys. */ @GridToStringInclude @GridDirectCollection(KeyCacheObject.class) private List failedKeys; /** Update error. */ @GridDirectTransient @GridToStringInclude private IgniteCheckedException err; /** Serialized update error. */ private byte[] errBytes; /** * */ public UpdateErrors() { // No-op. } /** * @param err Error. */ public UpdateErrors(IgniteCheckedException err) { assert err != null; this.err = err; } /** * @param err Error. */ public void onError(IgniteCheckedException err){ this.err = err; } /** * @return Error. */ public IgniteCheckedException error() { return err; } /** * @return Failed keys. */ public Collection failedKeys() { return failedKeys; } /** * Adds key to collection of failed keys. * * @param key Key to add. * @param e Error cause. */ void addFailedKey(KeyCacheObject key, Throwable e) { if (failedKeys == null) failedKeys = new ArrayList<>(); failedKeys.add(key); if (err == null) err = new IgniteCheckedException("Failed to update keys."); err.addSuppressed(e); } /** * @param keys Keys. * @param e Error. */ void addFailedKeys(Collection keys, Throwable e) { if (failedKeys == null) failedKeys = new ArrayList<>(keys.size()); failedKeys.addAll(keys); if (err == null) err = new IgniteCheckedException("Failed to update keys on primary node."); err.addSuppressed(e); } /** {@inheritDoc} */ void prepareMarshal(GridCacheMessage msg, GridCacheContext cctx) throws IgniteCheckedException { msg.prepareMarshalCacheObjects(failedKeys, cctx); if (errBytes == null) errBytes = U.marshal(cctx.marshaller(), err); } /** {@inheritDoc} */ void finishUnmarshal(GridCacheMessage msg, GridCacheContext cctx, ClassLoader ldr) throws IgniteCheckedException { msg.finishUnmarshalCacheObjects(failedKeys, cctx, ldr); if (errBytes != null && err == null) err = U.unmarshal(cctx.marshaller(), errBytes, U.resolveClassLoader(ldr, cctx.gridConfig())); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeByteArray("errBytes", errBytes)) return false; writer.incrementState(); case 1: if (!writer.writeCollection("failedKeys", failedKeys, MessageCollectionItemType.MSG)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: errBytes = reader.readByteArray("errBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: failedKeys = reader.readCollection("failedKeys", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(UpdateErrors.class); } /** {@inheritDoc} */ @Override public short directType() { return -49; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 2; } /** {@inheritDoc} */ @Override public void onAckReceived() { // No-op. } /** {@inheritDoc} */ @Override public String toString() { return S.toString(UpdateErrors.class, this); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 8111 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/UpdateErrors.java/#L41-L222 | 1 | 895 | 8111 | minor |
| 2458 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | f | f | f | blob | 0 | 14533 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 1 | 2458 | 14533 | minor | ||
| 1960 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 12583 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 2 | 1960 | 12583 | minor |
| 463 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Misplaced Class 5. Data Clumps 6. Primitive Obsession 7. Inappropriate Intimacy 8. Lazy Class 9. Middle Man 10. Message Chains 11. Shotgun Surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | Long Method 2 Feature Envy 3 Duplicate Code 4 Misplaced Class 5 Data Clumps 6 Primitive Obsession 7 Inappropriate Intimacy 8 Lazy Class 9 Middle Man | t | f | f | . Long Method 2. Feature Envy 3. Duplicate Code 4. Misplaced Class 5. Data Clumps 6. Primitive Obsession 7. Inappropriate Intimacy 8. Lazy Class 9. Middle Man | data class | 0 | 4487 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 2 | 463 | 4487 | minor |
| 916 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransactionIdConversion { static KahaTransactionInfo convertToLocal(TransactionId tx) { KahaTransactionInfo rc = new KahaTransactionInfo(); LocalTransactionId t = (LocalTransactionId) tx; KahaLocalTransactionId kahaTxId = new KahaLocalTransactionId(); kahaTxId.setConnectionId(t.getConnectionId().getValue()); kahaTxId.setTransactionId(t.getValue()); rc.setLocalTransactionId(kahaTxId); return rc; } static KahaTransactionInfo convert(TransactionId txid) { if (txid == null) { return null; } KahaTransactionInfo rc; if (txid.isLocalTransaction()) { rc = convertToLocal(txid); } else { rc = new KahaTransactionInfo(); XATransactionId t = (XATransactionId) txid; KahaXATransactionId kahaTxId = new KahaXATransactionId(); kahaTxId.setBranchQualifier(new Buffer(t.getBranchQualifier())); kahaTxId.setGlobalTransactionId(new Buffer(t.getGlobalTransactionId())); kahaTxId.setFormatId(t.getFormatId()); rc.setXaTransactionId(kahaTxId); } return rc; } static TransactionId convert(KahaTransactionInfo transactionInfo) { if (transactionInfo.hasLocalTransactionId()) { KahaLocalTransactionId tx = transactionInfo.getLocalTransactionId(); LocalTransactionId rc = new LocalTransactionId(); rc.setConnectionId(new ConnectionId(tx.getConnectionId())); rc.setValue(tx.getTransactionId()); return rc; } else { KahaXATransactionId tx = transactionInfo.getXaTransactionId(); XATransactionId rc = new XATransactionId(); rc.setBranchQualifier(tx.getBranchQualifier().toByteArray()); rc.setGlobalTransactionId(tx.getGlobalTransactionId().toByteArray()); rc.setFormatId(tx.getFormatId()); return rc; } } } |
blob | long method | t | t | f | long method | blob | 0 | 8247 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/TransactionIdConversion.java/#L29-L77 | 1 | 916 | 8247 | minor |
| 881 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainFragment extends Fragment implements Updatable { /** * The {@link SwipeRefreshLayout.OnRefreshListener} is also an {@link Observable}. It is * observed by the {@link UsernamesRepository}, an update is triggered whenever * {@link SwipeRefreshLayout.OnRefreshListener#onRefresh()} is fired. */ private OnRefreshObservable refreshObservable; /** * The {@link UsernamesRepository} takes care of providing the data to this fragment. It is an * {@link Updatable} because changes in the {@link OnRefreshObservable} require that it updates * its list of usernames. It is also an {@link Observable} and is observed by this MainFragment. */ private UsernamesRepository usernamesRepository; private ListAdapter listAdapter; private ListView listView; private SwipeRefreshLayout swipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.main_frag, container, false); listView = (ListView) root.findViewById(R.id.list); // Set pull to refresh as an observable and attach it to the view refreshObservable = new OnRefreshObservable(); swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.refresh_layout); swipeRefreshLayout.setColorSchemeColors( ContextCompat.getColor(getActivity(), R.color.colorPrimary), ContextCompat.getColor(getActivity(), R.color.colorAccent), ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark)); swipeRefreshLayout.setOnRefreshListener(refreshObservable); // Initialise the repository usernamesRepository = new UsernamesRepository(new UsernamesFetcher()); return root; } @Override public void onResume() { super.onResume(); // We make sure the repository observes the refresh listener refreshObservable.addUpdatable(usernamesRepository); /** * We make sure the main fragment observes the repository. This will also trigger the * repository to update itself, via * {@link UsernamesRepository#firstUpdatableAdded(UpdateDispatcher)}. */ usernamesRepository.addUpdatable(this); /** * We update the UI to show the data is being updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); } }); } @Override public void onPause() { super.onPause(); // We remove the observations to avoid triggering updates when they aren't needed refreshObservable.removeUpdatable(usernamesRepository); usernamesRepository.removeUpdatable(this); } /** * As this MainFragment is observing the {@link UsernamesRepository}, this is triggered * whenever the {@link UsernamesRepository} updates itself. */ @Override public void update() { /** * We update the UI to show the data has been updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as not refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); } }); // Check error status if (usernamesRepository.isError()) { // Show error message, do not update list as we still want to show the last known list of // usernames Toast.makeText(getContext(), getResources().getString(R.string.error), Toast.LENGTH_LONG).show(); } else { // Update the list of usernames listAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, usernamesRepository.get()); listView.setAdapter(listAdapter); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 8020 | https://github.com/google/agera/blob/04045ccbf41ac5fc6806724127b33cbe0dda372c/samples/BasicSample/app/src/main/java/com/example/android/agera/basicsample/MainFragment.java/#L42-L150 | 1 | 881 | 8020 | minor |
| 947 | YES I found bad smells. The bad smells are: Feature envy, Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Feature envy, Long method | t | f | f | Feature envy, Long method | data class | 0 | 8507 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 947 | 8507 | major |
| 639 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6330 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 639 | 6330 | critical |
| 25 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Key)) { return false; } Key key = (Key) o; return annotationType.equals(key.annotationType) && type.equals(key.type); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 693 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/commons/che-core-commons-inject/src/main/java/org/eclipse/che/inject/lifecycle/LifecycleModule.java/#L40-L50 | 1 | 25 | 693 | minor |
| 1920 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12413 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 1920 | 12413 | minor |
| 1939 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Data clumps 5. Long parameter list 6. Magic numbers 7. Duplicate code 8. Lazy class 9. Inappropriate variable names 10. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } } |
blob | Long method2 Feature envy3 Primitive obsession4 Data clumps5 Long parameter list6 Magic numbers7 Duplicate code8 Lazy class9 Inappropriate variable names | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Data clumps5. Long parameter list6. Magic numbers7. Duplicate code8. Lazy class9. Inappropriate variable names | blob | 0 | 12479 | https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 | 2 | 1939 | 12479 | major |
| 571 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DirContextType { private String name; private DirContextType(String name) { this.name = name; } public String toString() { return name; } /** * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); /** * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); } |
data class | Long method | t | f | f | .Long method | data class | 0 | 5739 | https://github.com/spring-projects/spring-ldap/blob/6a9bde34811b87b5425c05068a31ff61d7e59170/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java/#L30-L50 | 2 | 571 | 5739 | major |
| 2664 | YES I found bad smells the bad smells are: 1. Long method 2. Multiple if/else blocks without proper abstraction 3. Inconsistent indentation and code formatting 4. Lack of comments and documentation for the purpose of the method and parameters 5. Mixed use of instanceOf and casting in the condition 6. Hardcoded values and magic numbers for exceptions and return values | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
feature envy | Long method2 Multiple if/else blocks without proper abstraction3 Inconsistent indentation and code formatting4 Lack of comments and documentation for the purpose of the method and parameters5 Mixed use of instanceOf and casting in the condition6 Hardcoded values and magic numbers for exceptions and return values | t | f | f | . Long method2. Multiple if/else blocks without proper abstraction3. Inconsistent indentation and code formatting4. Lack of comments and documentation for the purpose of the method and parameters5. Mixed use of instanceOf and casting in the condition6. Hardcoded values and magic numbers for exceptions and return values | feature envy | 0 | 15200 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 2 | 2664 | 15200 | minor |
| 306 | " YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final static class Builder { private Supplier initialValue; private UnaryOperator splitOperator = null; private BinaryOperator mergeOperator = null; private Builder() { } public Builder initialValue(final Supplier initialValue) { this.initialValue = initialValue; return this; } public Builder splitOperator(final UnaryOperator splitOperator) { this.splitOperator = splitOperator; return this; } public Builder mergeOperator(final BinaryOperator mergeOperator) { this.mergeOperator = mergeOperator; return this; } public SackStrategy create() { return new SackStrategy(this.initialValue, this.splitOperator, this.mergeOperator); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3195 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/SackStrategy.java/#L58-L85 | 2 | 306 | 3195 | major |
| 2682 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 15268 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 2682 | 15268 | major |
| 142 | { "message": "YES I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1777 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 2 | 142 | 1777 | minor |
| 1191 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 10256 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 2 | 1191 | 10256 | minor |
| 4154 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Large interface 4. Inconsistent naming conventions 5. Excessive paramters in methods 6. Tight coupling 7. Lack of abstraction 8. No clear purpose or responsibility for the interface 9. Use of primitive types instead of object types in method parameters 10. Redundancy in method names (e.g. start and shutdown both refer to starting and stopping the model) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
blob | Long method 2 Feature envy 3 Large interface 4 Inconsistent naming conventions 5 Excessive paramters in methods 6 Tight coupling 7 Lack of abstraction 8 No clear purpose or responsibility for the interface 9 Use of primitive types instead of object types in method parameters | t | f | f | . Long method 2. Feature envy 3. Large interface 4. Inconsistent naming conventions 5. Excessive paramters in methods 6. Tight coupling 7. Lack of abstraction 8. No clear purpose or responsibility for the interface 9. Use of primitive types instead of object types in method parameters | blob | 0 | 10943 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 2 | 4154 | 10943 | minor |
| 1698 | YES I found bad smells the bad smells are: Feature envy: 1. Long method 2. Unnecessary comments 3. Poorly named variables (filename, offset) 4. Redundant code in the constructor 5. Mixing of business logic and exception handling code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | Long method 2 Unnecessary comments 3 Poorly named variables (filename, offset) 4 Redundant code in the constructor 5 Mixing of business logic and exception handling code | t | f | f | . Long method 2. Unnecessary comments 3. Poorly named variables (filename, offset) 4. Redundant code in the constructor 5. Mixing of business logic and exception handling code | data class | 0 | 11733 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 2 | 1698 | 11733 | minor |
| 2478 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14590 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 2478 | 14590 | major |
| 525 | YES I found bad smells the bad smells are: 1. Long class 2. Long method (createConsumer, onEvent, isMatching, isWildcarded) 3. Feature envy 4. Data class/misplaced responsibilities 5. Primitive obsession 6. Inappropriate intimacy 7. Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property) 8. Message chain (engine.start() accessed through multiple levels of abstraction) 9. Duplicated code (multiple if statements checking for wildcarded session identifier) 10. Dead code (some methods never called) 11. Comments suggesting magic values/hidden intent (// clear list of consumers) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
blob | Long class2 Long method (createConsumer, onEvent, isMatching, isWildcarded)3 Feature envy4 Data class/misplaced responsibilities5 Primitive obsession6 Inappropriate intimacy7 Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property)8 Message chain (enginestart() accessed through multiple levels of abstraction)9 Duplicated code (multiple if statements checking for wildcarded session identifier) | t | f | f | . Long class2. Long method (createConsumer, onEvent, isMatching, isWildcarded)3. Feature envy4. Data class/misplaced responsibilities5. Primitive obsession6. Inappropriate intimacy7. Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property)8. Message chain (engine.start() accessed through multiple levels of abstraction)9. Duplicated code (multiple if statements checking for wildcarded session identifier) | blob | 0 | 5430 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 2 | 525 | 5430 | minor |
| 2467 | YES I found bad smells The bad smells are: 1. Unused method 2. Unused variable | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | Unused method2 Unused variable | t | f | f | . Unused method2. Unused variable | data class | 0 | 14568 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 2 | 2467 | 14568 | major |
| 1371 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10800 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 2 | 1371 | 10800 | major |
| 1417 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10917 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 2 | 1417 | 10917 | minor |
| 2606 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 2606 | 15029 | major |
| 1192 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ZooInspectorPanel extends JPanel implements NodeViewersChangeListener { private final IconResource iconResource; private final Toolbar toolbar; private final ZooInspectorNodeViewersPanel nodeViewersPanel; private final ZooInspectorTreeViewer treeViewer; private final ZooInspectorManager zooInspectorManager; private final List listeners = new ArrayList(); { listeners.add(this); } /** * @param zooInspectorManager * - the {@link ZooInspectorManager} for the application */ public ZooInspectorPanel(final ZooInspectorManager zooInspectorManager, final IconResource iconResource) { this.zooInspectorManager = zooInspectorManager; this.iconResource = iconResource; toolbar = new Toolbar(iconResource); final List nodeViewers = new ArrayList(); try { List defaultNodeViewersClassNames = this.zooInspectorManager .getDefaultNodeViewerConfiguration(); for (String className : defaultNodeViewersClassNames) { nodeViewers.add((ZooInspectorNodeViewer) Class.forName( className).newInstance()); } } catch (Exception ex) { LoggerFactory.getLogger().error( "Error loading default node viewers.", ex); JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Error loading default node viewers: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } nodeViewersPanel = new ZooInspectorNodeViewersPanel( zooInspectorManager, nodeViewers); treeViewer = new ZooInspectorTreeViewer(zooInspectorManager, nodeViewersPanel, iconResource); this.setLayout(new BorderLayout()); toolbar.addActionListener(Toolbar.Button.connect, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorConnectionPropertiesDialog zicpd = new ZooInspectorConnectionPropertiesDialog( zooInspectorManager.getLastConnectionProps(), zooInspectorManager.getConnectionPropertiesTemplate(), ZooInspectorPanel.this); zicpd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.disconnect, new ActionListener() { public void actionPerformed(ActionEvent e) { disconnect(); } }); toolbar.addActionListener(Toolbar.Button.refresh, new ActionListener() { public void actionPerformed(ActionEvent e) { treeViewer.refreshView(); } }); toolbar.addActionListener(Toolbar.Button.addNode, new AddNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.deleteNode, new DeleteNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.nodeViewers, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorNodeViewersDialog nvd = new ZooInspectorNodeViewersDialog( JOptionPane.getRootFrame(), nodeViewers, listeners, zooInspectorManager, iconResource); nvd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.about, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorAboutDialog zicpd = new ZooInspectorAboutDialog( JOptionPane.getRootFrame(), iconResource); zicpd.setVisible(true); } }); JScrollPane treeScroller = new JScrollPane(treeViewer); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroller, nodeViewersPanel); splitPane.setResizeWeight(0.25); this.add(splitPane, BorderLayout.CENTER); this.add(toolbar.getJToolBar(), BorderLayout.NORTH); } /** * @param connectionProps * the {@link Properties} for connecting to the zookeeper * instance */ public void connect(final Properties connectionProps) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { zooInspectorManager.setLastConnectionProps(connectionProps); return zooInspectorManager.connect(connectionProps); } @Override protected void done() { try { if (get()) { treeViewer.refreshView(); toolbar.toggleButtons(true); } else { JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Unable to connect to zookeeper", "Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } } }; worker.execute(); } /** * */ public void disconnect() { disconnect(false); } /** * @param wait * - set this to true if the method should only return once the * application has successfully disconnected */ public void disconnect(boolean wait) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { return ZooInspectorPanel.this.zooInspectorManager.disconnect(); } @Override protected void done() { try { if (get()) { treeViewer.clearView(); toolbar.toggleButtons(false); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } }; worker.execute(); if (wait) { while (!worker.isDone()) { try { Thread.sleep(100); } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } } } /* * (non-Javadoc) * * @seeorg.apache.zookeeper.inspector.gui.NodeViewersChangeListener# * nodeViewersChanged(java.util.List) */ public void nodeViewersChanged(List newViewers) { this.nodeViewersPanel.setNodeViewers(newViewers); } /** * @param connectionProps * @throws IOException */ public void setdefaultConnectionProps(Properties connectionProps) throws IOException { this.zooInspectorManager.saveDefaultConnectionFile(connectionProps); } } |
blob | f | f | f | blob | 0 | 10257 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/org/apache/zookeeper/inspector/gui/ZooInspectorPanel.java/#L46-L258 | 2 | 1192 | 10257 | minor | ||
| 1349 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10754 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 1349 | 10754 | minor |
| 1134 | YES I found bad smells The bad smells are: 1. Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself. 2. Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization. 3. Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions. 4. Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers. 5. Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability. 6. Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself2 Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization3 Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions4 Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers5 Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability6 Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter | t | f | f | . Feature envy: The methods getName(), isPrimitive(), getValue(), and getType() all use the jdiVariable object extensively, indicating that they may be better suited for the JdbVariable class itself.2. Long parameter list: The constructor for JdbVariable has two parameters which could potentially be condensed into one object for better organization.3. Inconsistent naming conventions: Some variables are named with a prefix of "jdi" while others are not, indicating a lack of consistency in naming conventions.4. Lack of comments: There are no comments or explanatory comments in the code, making it difficult to understand for other developers.5. Use of ternary operator: The ternary operator used in the constructor for value can be confusing and could potentially be rewritten for better readability.6. Redundant code: The constructor for JdbVariable could potentially be combined with the second constructor by setting a default value for the jdiVariable parameter. | data class | 0 | 10054 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 2 | 1134 | 10054 | minor |
| 435 | YES I found bad smells- 1.Long method, 2.Magic number, 3.Creation method, 4.Feature envy, 5.Long parameter list, 6.Inappropriate intimacy, 7.Missing or unclear JavaDoc, 8.Unnecessary comments, 9.Data clumps, 10.Long nested blocks, 11.Data class, 12. Inappropriate use of variables, 13.Useless override, 14.Switch statement, 15.Message chains, 16.Duplicated code, 17.Missing type declaration, 18.Illegal catch statement, 19.Inefficient return, 20.Large Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
data class | Long method, 2Magic number, 3Creation method, 4Feature envy, 5Long parameter list, 6Inappropriate intimacy, 7Missing or unclear JavaDoc, 8Unnecessary comments, 9Data clumps, | t | f | f | .Long method, 2.Magic number, 3.Creation method, 4.Feature envy, 5.Long parameter list, 6.Inappropriate intimacy, 7.Missing or unclear JavaDoc, 8.Unnecessary comments, 9.Data clumps, | data class | 0 | 4284 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 2 | 435 | 4284 | major |
| 151 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 1911 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 1 | 151 | 1911 | major |
| 3946 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 10325 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 1 | 3946 | 10325 | critical | ||
| 496 | {"response": "YES I found bad smells", "bad_smells": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DiscoverAnnotatedBeans implements DynamicDeployer { public AppModule deploy(AppModule appModule) throws OpenEJBException { for (EjbModule ejbModule : appModule.getEjbModules()) { ejbModule.initAppModule(appModule); setModule(ejbModule); try { deploy(ejbModule); } finally { removeModule(); } } for (ClientModule clientModule : appModule.getClientModules()) { clientModule.initAppModule(appModule); setModule(clientModule); try { deploy(clientModule); } finally { removeModule(); } } for (ConnectorModule connectorModule : appModule.getConnectorModules()) { connectorModule.initAppModule(appModule); setModule(connectorModule); try { deploy(connectorModule); } finally { removeModule(); } } for (WebModule webModule : appModule.getWebModules()) { webModule.initAppModule(appModule); setModule(webModule); try { deploy(webModule); } finally { removeModule(); } } final AdditionalBeanDiscoverer discoverer = SystemInstance.get().getComponent(AdditionalBeanDiscoverer.class); if (discoverer != null) { appModule = discoverer.discover(appModule); } return appModule; } public ClientModule deploy(ClientModule clientModule) throws OpenEJBException { if (clientModule.getApplicationClient() == null){ clientModule.setApplicationClient(new ApplicationClient()); } // Lots of jars have main classes so this might not even be an app client. // We're not going to scrape it for @LocalClient or @RemoteClient annotations // unless they flag us specifically by adding a META-INF/application-client.xml // // ClientModules that already have a AnnotationFinder have been generated automatically // from an EjbModule, so we don't skip those ever. if (clientModule.getFinder() == null && clientModule.getAltDDs().containsKey("application-client.xml")) if (clientModule.getApplicationClient() != null && clientModule.getApplicationClient().isMetadataComplete()) return clientModule; IAnnotationFinder finder = clientModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(clientModule); } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForClientModule.url", clientModule.getJarLocation()); return clientModule; } catch (Exception e) { startupLogger.warning("startup.scrapeFailedForClientModule", e, clientModule.getJarLocation()); return clientModule; } } // This method is also called by the deploy(EjbModule) method to see if those // modules have any @LocalClient or @RemoteClient classes for (Annotated> clazz : finder.findMetaAnnotatedClasses(LocalClient.class)) { clientModule.getLocalClients().add(clazz.get().getName()); } for (Annotated> clazz : finder.findMetaAnnotatedClasses(RemoteClient.class)) { clientModule.getRemoteClients().add(clazz.get().getName()); } if (clientModule.getApplicationClient() == null){ if (clientModule.getRemoteClients().size() > 0 || clientModule.getLocalClients().size() > 0) { clientModule.setApplicationClient(new ApplicationClient()); } } return clientModule; } public ConnectorModule deploy(ConnectorModule connectorModule) throws OpenEJBException { org.apache.openejb.jee.Connector connector = connectorModule.getConnector(); if (connector == null) { connector = new org.apache.openejb.jee.Connector(); } // JCA 1.6 - 18.3.1 do not look at annotations if the provided connector // deployment descriptor is "meta-data complete". float specVersion = 0; try { specVersion = Float.parseFloat(connector.getVersion()); } catch (Exception e) { } if (specVersion < 1.6 || Boolean.TRUE.equals(connector.isMetadataComplete())) { return connectorModule; } IAnnotationFinder finder = connectorModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(connectorModule); connectorModule.setFinder(finder); } catch (Exception e) { // TODO: some sort of error return connectorModule; } } List> connectorClasses = finder.findAnnotatedClasses(Connector.class); // are we allowed to have more than one connector class? Not without a deployment descriptor if (connector.getResourceAdapter() == null || connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { if (connectorClasses.size() == 0) { // fail some validation here too } if (connectorClasses.size() > 1) { // too many connector classes, this is against the spec // something like connectorModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); } } Class connectorClass = null; if (connectorClasses.size() == 1) { connectorClass = connectorClasses.get(0); } if (connectorClasses.size() > 1) { for (Class cls : connectorClasses) { if (cls.getName().equals(connector.getResourceAdapter().getResourceAdapterClass())) { connectorClass = cls; break; } } } if (connectorClass != null) { if (connector.getResourceAdapter() == null) { connector.setResourceAdapter(new ResourceAdapter()); } if (connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { connector.getResourceAdapter().setResourceAdapterClass(connectorClass.getName()); } Connector connectorAnnotation = connectorClass.getAnnotation(Connector.class); connector.setDisplayNames(getTexts(connector.getDisplayNames(), connectorAnnotation.displayName())); connector.setDescriptions(getTexts(connector.getDescriptions(), connectorAnnotation.description())); connector.setEisType(getString(connector.getEisType(), connectorAnnotation.eisType())); connector.setVendorName(getString(connector.getVendorName(), connectorAnnotation.vendorName())); connector.setResourceAdapterVersion(getString(connector.getResourceAdapterVersion(), connectorAnnotation.version())); if (connector.getIcons().isEmpty()) { int smallIcons = connectorAnnotation.smallIcon().length; int largeIcons = connectorAnnotation.largeIcon().length; for (int i = 0; i < smallIcons && i < largeIcons; i++) { Icon icon = new Icon(); // locale can't be specified in the annotation and it is en by default // so on other systems it doesn't work because Icon return the default locale icon.setLang(Locale.getDefault().getLanguage()); if (i < smallIcons) { icon.setSmallIcon(connectorAnnotation.smallIcon()[i]); } if (i < largeIcons) { icon.setLargeIcon(connectorAnnotation.largeIcon()[i]); } connector.getIcons().add(icon); } } if (connector.getLicense() == null) { License license = new License(); connector.setLicense(license); license.setLicenseRequired(connectorAnnotation.licenseRequired()); } connector.getLicense().setDescriptions(getTexts(connector.getLicense().getDescriptions(), connectorAnnotation.licenseDescription())); SecurityPermission[] annotationSecurityPermissions = connectorAnnotation.securityPermissions(); List securityPermission = connector.getResourceAdapter().getSecurityPermission(); if (securityPermission == null || securityPermission.size() == 0) { for (SecurityPermission sp : annotationSecurityPermissions) { org.apache.openejb.jee.SecurityPermission permission = new org.apache.openejb.jee.SecurityPermission(); permission.setSecurityPermissionSpec(sp.permissionSpec()); permission.setDescriptions(stringsToTexts(sp.description())); securityPermission.add(permission); } } Class[] annotationRequiredWorkContexts = connectorAnnotation.requiredWorkContexts(); List requiredWorkContext = connector.getRequiredWorkContext(); if (requiredWorkContext.size() == 0) { for (Class cls : annotationRequiredWorkContexts) { requiredWorkContext.add(cls.getName()); } } OutboundResourceAdapter outboundResourceAdapter = connector.getResourceAdapter().getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); connector.getResourceAdapter().setOutboundResourceAdapter(outboundResourceAdapter); } List authenticationMechanisms = outboundResourceAdapter.getAuthenticationMechanism(); javax.resource.spi.AuthenticationMechanism[] authMechanisms = connectorAnnotation.authMechanisms(); if (authenticationMechanisms.size() == 0) { for (javax.resource.spi.AuthenticationMechanism am : authMechanisms) { AuthenticationMechanism authMechanism = new AuthenticationMechanism(); authMechanism.setAuthenticationMechanismType(am.authMechanism()); authMechanism.setCredentialInterface(am.credentialInterface().toString()); authMechanism.setDescriptions(stringsToTexts(am.description())); authenticationMechanisms.add(authMechanism); } } if (outboundResourceAdapter.getTransactionSupport() == null) { outboundResourceAdapter.setTransactionSupport(TransactionSupportType.fromValue(connectorAnnotation.transactionSupport().toString())); } if (outboundResourceAdapter.isReauthenticationSupport() == null) { outboundResourceAdapter.setReauthenticationSupport(connectorAnnotation.reauthenticationSupport()); } } else { // we couldn't process a connector class - probably a validation issue which we should warn about. } // process @ConnectionDescription(s) List> classes = finder.findAnnotatedClasses(ConnectionDefinitions.class); for (Class cls : classes) { ConnectionDefinitions connectionDefinitionsAnnotation = cls.getAnnotation(ConnectionDefinitions.class); ConnectionDefinition[] definitions = connectionDefinitionsAnnotation.value(); for (ConnectionDefinition definition : definitions) { processConnectionDescription(connector.getResourceAdapter(), definition, cls); } } classes = finder.findAnnotatedClasses(ConnectionDefinition.class); for (Class cls : classes) { ConnectionDefinition connectionDefinitionAnnotation = cls.getAnnotation(ConnectionDefinition.class); processConnectionDescription(connector.getResourceAdapter(), connectionDefinitionAnnotation, cls); } InboundResourceadapter inboundResourceAdapter = connector.getResourceAdapter().getInboundResourceAdapter(); if (inboundResourceAdapter == null) { inboundResourceAdapter = new InboundResourceadapter(); connector.getResourceAdapter().setInboundResourceAdapter(inboundResourceAdapter); } MessageAdapter messageAdapter = inboundResourceAdapter.getMessageAdapter(); if (messageAdapter == null) { messageAdapter = new MessageAdapter(); inboundResourceAdapter.setMessageAdapter(messageAdapter); } classes = finder.findAnnotatedClasses(Activation.class); for (Class cls : classes) { MessageListener messageListener = null; Activation activationAnnotation = cls.getAnnotation(Activation.class); List messageListeners = messageAdapter.getMessageListener(); for (MessageListener ml : messageListeners) { if (cls.getName().equals(ml.getActivationSpec().getActivationSpecClass())) { messageListener = ml; break; } } if (messageListener == null) { Class[] listeners = activationAnnotation.messageListeners(); for (Class listener : listeners) { messageAdapter.addMessageListener(new MessageListener(listener.getName(), cls.getName())); } } } classes = finder.findAnnotatedClasses(AdministeredObject.class); List adminObjects = connector.getResourceAdapter().getAdminObject(); for (Class cls : classes) { AdministeredObject administeredObjectAnnotation = cls.getAnnotation(AdministeredObject.class); Class[] adminObjectInterfaces = administeredObjectAnnotation.adminObjectInterfaces(); AdminObject adminObject = null; for (AdminObject admObj : adminObjects) { if (admObj.getAdminObjectClass().equals(cls.getName())) { adminObject = admObj; } } if (adminObject == null) { for (Class iface : adminObjectInterfaces) { AdminObject newAdminObject = new AdminObject(); newAdminObject.setAdminObjectClass(cls.getName()); newAdminObject.setAdminObjectInterface(iface.getName()); adminObjects.add(newAdminObject); } } } // need to make a list of classes to process for config properties // resource adapter String raCls = connector.getResourceAdapter().getResourceAdapterClass(); process(connectorModule.getClassLoader(), raCls, connector.getResourceAdapter()); // managedconnectionfactory if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getOutboundResourceAdapter() != null) { List connectionDefinitions = connector.getResourceAdapter().getOutboundResourceAdapter().getConnectionDefinition(); for (org.apache.openejb.jee.ConnectionDefinition connectionDefinition : connectionDefinitions) { process(connectorModule.getClassLoader(), connectionDefinition.getManagedConnectionFactoryClass(), connectionDefinition); } } // administeredobject if (connector.getResourceAdapter() != null) { List raAdminObjects = connector.getResourceAdapter().getAdminObject(); for (AdminObject raAdminObject : raAdminObjects) { process(connectorModule.getClassLoader(), raAdminObject.getAdminObjectClass(), raAdminObject); } } // activationspec if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter() != null) { List messageListeners = connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter().getMessageListener(); for (MessageListener messageListener : messageListeners) { ActivationSpec activationSpec = messageListener.getActivationSpec(); process(connectorModule.getClassLoader(), activationSpec.getActivationSpecClass(), activationSpec); } } return connectorModule; } void process(ClassLoader cl, String cls, Object object) { List configProperties = null; try { // grab a list of ConfigProperty objects configProperties = (List) object.getClass().getDeclaredMethod("getConfigProperty").invoke(object); } catch (Exception e) { } if (configProperties == null) { // can't get config properties return; } ClassLoader classLoader = cl; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final List allowedTypes = Arrays.asList(new String[] { Boolean.class.getName(), String.class.getName(), Integer.class.getName(), Double.class.getName(), Byte.class.getName(), Short.class.getName(), Long.class.getName(), Float.class.getName(), Character.class.getName()}); try { Class clazz = classLoader.loadClass(realClassName(cls)); Object o = clazz.newInstance(); // add any introspected properties BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); Class type = propertyDescriptor.getPropertyType(); if (type == null) { continue; } if (type.isPrimitive()) { type = getWrapper(type.getName()); } if (! allowedTypes.contains(type.getName())) { continue; } if (! containsConfigProperty(configProperties, name)) { if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); Object value = null; try { value = propertyDescriptor.getReadMethod().invoke(o); } catch (Exception e) { } javax.resource.spi.ConfigProperty annotation = propertyDescriptor.getWriteMethod().getAnnotation(javax.resource.spi.ConfigProperty.class); if (annotation == null) { try { // if there's no annotation on the setter, we'll try and scrape one off the field itself (assuming the same name) annotation = clazz.getDeclaredField(name).getAnnotation(javax.resource.spi.ConfigProperty.class); } catch (Exception ignored) { // no-op : getDeclaredField() throws exceptions and does not return null } } configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(getConfigPropertyType(annotation, type)); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null && annotation.defaultValue().length() > 0) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); configProperty.setDescriptions(stringsToTexts(annotation.description())); } } } } // add any annotated fields we haven't already picked up Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { javax.resource.spi.ConfigProperty annotation = field.getAnnotation(javax.resource.spi.ConfigProperty.class); String name = field.getName(); Object value = null; try { value = field.get(o); } catch (Exception e) { } if (! containsConfigProperty(configProperties, name)) { String type = getConfigPropertyType(annotation, field.getType()); if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(type); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); } } } } } catch (Exception e) { e.printStackTrace(); } } private String getConfigPropertyType(javax.resource.spi.ConfigProperty annotation, Class type) { Class t = (annotation == null) ? null : annotation.type(); if (t == null && type != null) { return type.getName(); } else if (t == null) { return null; } if (t.equals(Object.class)) { t = type; } if (t == null) { // t == null && type == null return null; } if (t.isPrimitive()) { t = getWrapper(t.getName()); } return t.getName(); } private boolean containsConfigProperty(List configProperties, String name) { for (ConfigProperty configProperty : configProperties) { if (configProperty.getConfigPropertyName().equals(name)) { return true; } } return false; } private Class getWrapper(String primitiveType) { final Map> builtInMap = new HashMap>();{ builtInMap.put("int", Integer.class); builtInMap.put("long", Long.class); builtInMap.put("double", Double.class); builtInMap.put("float", Float.class); builtInMap.put("boolean", Boolean.class); builtInMap.put("char", Character.class); builtInMap.put("byte", Byte.class); builtInMap.put("void", Void.class); builtInMap.put("short", Short.class); } return builtInMap.get(primitiveType); } private void processConnectionDescription(ResourceAdapter resourceAdapter, ConnectionDefinition connectionDefinitionAnnotation, Class cls) { // try and find the managed connection factory OutboundResourceAdapter outboundResourceAdapter = resourceAdapter.getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); resourceAdapter.setOutboundResourceAdapter(outboundResourceAdapter); } List connectionDefinition = outboundResourceAdapter.getConnectionDefinition(); org.apache.openejb.jee.ConnectionDefinition definition = null; for (org.apache.openejb.jee.ConnectionDefinition cd : connectionDefinition) { if (cd.getManagedConnectionFactoryClass().equals(cls.getName())) { definition = cd; break; } } if (definition == null) { definition = new org.apache.openejb.jee.ConnectionDefinition(); outboundResourceAdapter.getConnectionDefinition().add(definition); } if (definition.getManagedConnectionFactoryClass() == null) { definition.setManagedConnectionFactoryClass(cls.getName()); } if (definition.getConnectionInterface() == null) { definition.setConnectionInterface(connectionDefinitionAnnotation.connection().getName()); } if (definition.getConnectionImplClass() == null) { definition.setConnectionImplClass(connectionDefinitionAnnotation.connectionImpl().getName()); } if (definition.getConnectionFactoryInterface() == null) { definition.setConnectionFactoryInterface(connectionDefinitionAnnotation.connectionFactory().getName()); } if (definition.getConnectionFactoryImplClass() == null) { definition.setConnectionFactoryImplClass(connectionDefinitionAnnotation.connectionFactoryImpl().getName()); } } private Text[] stringsToTexts(String[] strings) { if (strings == null) { return null; } Text[] result = new Text[strings.length]; for (int i = 0; i < result.length; i++) { result[i] = new Text(); result[i].setValue(strings[i]); } return result; } private String getString(String descriptorString, String annotationString) { if (descriptorString != null && descriptorString.length() > 0) { return descriptorString; } if (annotationString != null && annotationString.length() > 0) { return annotationString; } return null; } private Text[] getTexts(Text[] originalTexts, String[] newStrings) { if (newStrings != null && newStrings.length > 0 && (originalTexts == null || originalTexts.length == 0)) { Text[] texts = new Text[newStrings.length]; for (int i = 0; i < newStrings.length; i++) { texts[i] = new Text(null, newStrings[i]); } return texts; } else { return originalTexts; } } public WebModule deploy(WebModule webModule) throws OpenEJBException { WebApp webApp = webModule.getWebApp(); if (webApp != null && (webApp.isMetadataComplete())) return webModule; try { if (webModule.getFinder() == null) { webModule.setFinder(FinderFactory.createFinder(webModule)); } } catch (Exception e) { startupLogger.warning("Unable to scrape for @WebService or @WebServiceProvider annotations. AnnotationFinder failed.", e); return webModule; } if (webApp == null) { webApp = new WebApp(); webModule.setWebApp(webApp); } List existingServlets = new ArrayList(); for (Servlet servlet : webApp.getServlet()) { if (servlet.getServletClass() != null) { existingServlets.add(servlet.getServletClass()); } } IAnnotationFinder finder = webModule.getFinder(); List classes = new ArrayList(); classes.addAll(finder.findAnnotatedClasses(WebService.class)); classes.addAll(finder.findAnnotatedClasses(WebServiceProvider.class)); for (Class webServiceClass : classes) { // If this class is also annotated @Stateless or @Singleton, we should skip it if (webServiceClass.isAnnotationPresent(Singleton.class) || webServiceClass.isAnnotationPresent(Stateless.class)) { webModule.getEjbWebServices().add(webServiceClass.getName()); continue; } int modifiers = webServiceClass.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || isAbstract(modifiers)) { continue; } if (existingServlets.contains(webServiceClass.getName())) continue; // create webApp and webservices objects if they don't exist already // add new element Servlet servlet = new Servlet(); servlet.setServletName(webServiceClass.getName()); servlet.setServletClass(webServiceClass.getName()); webApp.getServlet().add(servlet); } /* * REST */ // get by annotations webModule.getRestClasses().addAll(findRestClasses(webModule, finder)); addJaxRsProviders(finder, webModule.getJaxrsProviders(), Provider.class); // Applications with a default constructor // findSubclasses will not work by default to gain a lot of time // look FinderFactory for the flag to activate it or // use @ApplicationPath("/") List> applications = finder.findSubclasses(Application.class); for (Class app : applications) { addRestApplicationIfPossible(webModule, app); } // look for ApplicationPath, it will often return the same than the previous one // but without finder.link() invocation it still works // so it can save a lot of startup time List>> applicationsByAnnotation = finder.findMetaAnnotatedClasses(ApplicationPath.class); for (Annotated> annotatedApp : applicationsByAnnotation) { final Class app = annotatedApp.get(); if (!Application.class.isAssignableFrom(app)) { logger.error("class '" + app.getName() + "' is annotated with @ApplicationPath but doesn't implement " + Application.class.getName()); continue; } addRestApplicationIfPossible(webModule, (Class) app); } /* * JSF */ final ClassLoader classLoader = webModule.getClassLoader(); for (String jsfClass : JSF_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(jsfClass); } catch (ClassNotFoundException e) { continue; } final List>> found = finder.findMetaAnnotatedClasses(clazz); final Set convertedClasses = new HashSet(found.size()); for (Annotated> annotated : found) { convertedClasses.add(annotated.get().getName()); } webModule.getJsfAnnotatedClasses().put(jsfClass, convertedClasses); } /* * Servlet, Filter, Listener */ Map urlByClasses = null; for (String apiClassName : WEB_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(apiClassName); } catch (ClassNotFoundException e) { continue; } if (urlByClasses == null) { // try to reuse scanning info, maybe some better indexing can be a nice idea if (finder instanceof FinderFactory.ModuleLimitedFinder) { final IAnnotationFinder limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (limitedFinder instanceof AnnotationFinder) { final Archive archive = ((AnnotationFinder) limitedFinder).getArchive(); if (archive instanceof WebappAggregatedArchive) { final Map> index = ((WebappAggregatedArchive) archive).getClassesMap(); urlByClasses = new HashMap(); for (Map.Entry> entry : index.entrySet()) { final String url = entry.getKey().toExternalForm(); for (String current : entry.getValue()) { urlByClasses.put(current, url); } } } } } } final List>> found = finder.findMetaAnnotatedClasses(clazz); addWebAnnotatedClassInfo(urlByClasses, webModule.getWebAnnotatedClasses(), found); } if (urlByClasses != null) { urlByClasses.clear(); } return webModule; } private void addJaxRsProviders(final IAnnotationFinder finder, final Collection set, final Class annotation) { for (Annotated> provider : finder.findMetaAnnotatedClasses(annotation)) { set.add(provider.get().getName()); } } private static void addRestApplicationIfPossible(final WebModule webModule, final Class app) { if (app.getConstructors().length == 0) { webModule.getRestApplications().add(app.getName()); } else { for (Constructor ctr : app.getConstructors()) { if (ctr.getParameterTypes().length == 0) { webModule.getRestApplications().add(app.getName()); break; } } } } public EjbModule deploy(EjbModule ejbModule) throws OpenEJBException { if (ejbModule.getEjbJar() != null && ejbModule.getEjbJar().isMetadataComplete()) return ejbModule; try { if (ejbModule.getFinder() == null) { ejbModule.setFinder(FinderFactory.createFinder(ejbModule)); } } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForModule", ejbModule.getJarLocation()); return ejbModule; } catch (Exception e) { startupLogger.warning("Unable to scrape for @Stateful, @Stateless, @Singleton or @MessageDriven annotations. AnnotationFinder failed.", e); return ejbModule; } IAnnotationFinder finder = ejbModule.getFinder(); final List managedClasses; { final Beans beans = ejbModule.getBeans(); if (beans != null) { managedClasses = beans.getManagedClasses(); final List classNames = getBeanClasses(finder); for (String rawClassName : classNames) { final String className = realClassName(rawClassName); try { final ClassLoader loader = ejbModule.getClassLoader(); final Class clazz = loader.loadClass(className); // The following can NOT be beans in CDI // 1. Non-static inner classes if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) continue; // // // 2. Abstract classes (unless they are an @Decorator) // if (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isAnnotationPresent(javax.decorator.Decorator.class)) continue; // // 3. Implementations of Extension if (Extension.class.isAssignableFrom(clazz)) continue; managedClasses.add(className); } catch (ClassNotFoundException e) { // todo log debug warning } catch (java.lang.NoClassDefFoundError e) { // no-op } } // passing jar location to be able to manage maven classes/test-classes which have the same moduleId String id = ejbModule.getModuleId(); if (ejbModule.getJarLocation() != null && ejbModule.getJarLocation().contains(ejbModule.getModuleId() + "/target/test-classes".replace("/", File.separator))) { // with maven if both src/main/java and src/test/java are deployed // moduleId.Comp exists twice so it fails // here we simply modify the test comp bean name to avoid it id += "_test"; } final String name = BeanContext.Comp.openejbCompName(id); final org.apache.openejb.jee.ManagedBean managedBean = new CompManagedBean(name, BeanContext.Comp.class); managedBean.setTransactionType(TransactionType.BEAN); ejbModule.getEjbJar().addEnterpriseBean(managedBean); } else { managedClasses = new ArrayList(); } } final Set> specializingClasses = new HashSet>(); // Fill in default sessionType for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (!(bean instanceof SessionBean)) continue; SessionBean sessionBean = (SessionBean) bean; if (sessionBean.getSessionType() != null) continue; try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); sessionBean.setSessionType(getSessionType(clazz)); } catch (Throwable handledInValidation) { // no-op } } // Fill in default ejbName for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (bean.getEjbClass() == null) continue; if (bean.getEjbName() == null || bean.getEjbName().startsWith("@NULL@")) { ejbModule.getEjbJar().removeEnterpriseBean(bean.getEjbName()); try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); final String ejbName = getEjbName(bean, clazz); bean.setEjbName(ejbName); } catch (Throwable handledInValidation) { } ejbModule.getEjbJar().addEnterpriseBean(bean); } } /* 19.2: ejb-name: Default is the unqualified name of the bean class */ EjbJar ejbJar = ejbModule.getEjbJar(); for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Singleton.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Singleton singleton = beanClass.getAnnotation(Singleton.class); String ejbName = getEjbName(singleton, beanClass.get()); if (!isValidEjbAnnotationUsage(Singleton.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new SingletonBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.SINGLETON); if (singleton.mappedName() != null) { sessionBean.setMappedName(singleton.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateless.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateless stateless = beanClass.getAnnotation(Stateless.class); String ejbName = getEjbName(stateless, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateless.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatelessBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.STATELESS); if (stateless.mappedName() != null) { sessionBean.setMappedName(stateless.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } // The Specialization code is good, but it possibly needs to be moved to after the full processing of the bean // the plus is that it would get the required interfaces. The minus is that it would get all the other items // Possibly study alternatives. Alternatives might have different meta data completely while it seems Specializing beans inherit all meta-data // Anyway.. the qualifiers aren't getting inherited, so we need to fix that for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateful.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateful stateful = beanClass.getAnnotation(Stateful.class); String ejbName = getEjbName(stateful, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateful.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatefulBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; // TODO: We might be stepping on an xml override here sessionBean.setSessionType(SessionType.STATEFUL); if (stateful.mappedName() != null) { sessionBean.setMappedName(stateful.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(ManagedBean.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } ManagedBean managed = beanClass.getAnnotation(ManagedBean.class); String ejbName = getEjbName(managed, beanClass.get()); // TODO: this is actually against the spec, but the requirement is rather silly // (allowing @Stateful and @ManagedBean on the same class) // If the TCK doesn't complain we should discourage it if (!isValidEjbAnnotationUsage(ManagedBean.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new org.apache.openejb.jee.ManagedBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.MANAGED); final TransactionType transactionType = sessionBean.getTransactionType(); if (transactionType == null) sessionBean.setTransactionType(TransactionType.BEAN); } } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(MessageDriven.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } MessageDriven mdb = beanClass.getAnnotation(MessageDriven.class); String ejbName = getEjbName(mdb, beanClass.get()); if (!isValidEjbAnnotationUsage(MessageDriven.class, beanClass, ejbName, ejbModule)) continue; MessageDrivenBean messageBean = (MessageDrivenBean) ejbJar.getEnterpriseBean(ejbName); if (messageBean == null) { messageBean = new MessageDrivenBean(ejbName); ejbJar.addEnterpriseBean(messageBean); } if (messageBean.getEjbClass() == null) { messageBean.setEjbClass(beanClass.get()); } LegacyProcessor.process(beanClass.get(), messageBean); } for (Class specializingClass : sortClassesParentFirst(new ArrayList>(specializingClasses))) { final Class parent = specializingClass.getSuperclass(); if (parent == null || parent.equals(Object.class)) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsNothing", specializingClass.getName()); } boolean found = false; for (EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) { final String ejbClass = enterpriseBean.getEjbClass(); if (ejbClass != null && ejbClass.equals(parent.getName())) { managedClasses.remove(ejbClass); enterpriseBean.setEjbClass(specializingClass.getName()); found = true; } } if (!found) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsSimpleBean", specializingClass.getName()); } } AssemblyDescriptor assemblyDescriptor = ejbModule.getEjbJar().getAssemblyDescriptor(); if (assemblyDescriptor == null) { assemblyDescriptor = new AssemblyDescriptor(); ejbModule.getEjbJar().setAssemblyDescriptor(assemblyDescriptor); } startupLogger.debug("Searching for annotated application exceptions (see OPENEJB-980)"); List> appExceptions = finder.findAnnotatedClasses(ApplicationException.class); for (Class exceptionClass : appExceptions) { startupLogger.debug("...handling " + exceptionClass); ApplicationException annotation = exceptionClass.getAnnotation(ApplicationException.class); if (assemblyDescriptor.getApplicationException(exceptionClass) == null) { startupLogger.debug("...adding " + exceptionClass + " with rollback=" + annotation.rollback()); assemblyDescriptor.addApplicationException(exceptionClass, annotation.rollback(), annotation.inherited()); } else { mergeApplicationExceptionAnnotation(assemblyDescriptor, exceptionClass, annotation); } } // ejb can be rest bean and only then in standalone so scan providers here too // adding them to app since they should be in the app classloader if (ejbModule.getAppModule() != null) { addJaxRsProviders(finder, ejbModule.getAppModule().getJaxRsProviders(), Provider.class); } if (ejbModule.getAppModule() != null) { for (PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) { for (org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) { if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses()) && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) { final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE); // no need of meta currently since JPA providers doesn't support it final List> classes = new ArrayList>(); classes.addAll(finder.findAnnotatedClasses(Entity.class)); classes.addAll(finder.findAnnotatedClasses(Embeddable.class)); classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class)); final List existingClasses = pu.getClazz(); for (Class clazz : classes) { final String name = clazz.getName(); if ((packageName == null || name.startsWith(packageName)) && !existingClasses.contains(name)) { pu.getClazz().add(name); } } pu.setScanned(true); } } } } return ejbModule; } private SessionType getSessionType(Class clazz) { if (clazz.isAnnotationPresent(Stateful.class)) return SessionType.STATEFUL; if (clazz.isAnnotationPresent(Stateless.class)) return SessionType.STATELESS; if (clazz.isAnnotationPresent(Singleton.class)) return SessionType.SINGLETON; if (clazz.isAnnotationPresent(ManagedBean.class)) return SessionType.MANAGED; return null; } private String getEjbName(EnterpriseBean bean, Class clazz) { if (bean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) bean; switch (sessionBean.getSessionType()) { case STATEFUL: { final Stateful annotation = clazz.getAnnotation(Stateful.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case STATELESS: { final Stateless annotation = clazz.getAnnotation(Stateless.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case SINGLETON: { final Singleton annotation = clazz.getAnnotation(Singleton.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } } } if (bean instanceof MessageDrivenBean) { final MessageDriven annotation = clazz.getAnnotation(MessageDriven.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } return clazz.getSimpleName(); } private static boolean specified(final String name) { return name != null && name.length() != 0; } private List getBeanClasses(IAnnotationFinder finder) { // What we're hoping in this method is to get lucky and find // that our 'finder' instances is an AnnotationFinder that is // holding an AggregatedArchive so we can get the classes that // that pertain to each URL for CDI purposes. // // If not we call finder.getAnnotatedClassNames() which may return // more classes than actually apply to CDI. This can "pollute" // the CDI class space and break injection points if (!(finder instanceof FinderFactory.ModuleLimitedFinder)) return finder.getAnnotatedClassNames(); final IAnnotationFinder delegate = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (!(delegate instanceof AnnotationFinder)) return finder.getAnnotatedClassNames(); final AnnotationFinder annotationFinder = (AnnotationFinder) delegate; final Archive archive = annotationFinder.getArchive(); if (!(archive instanceof WebappAggregatedArchive)) return finder.getAnnotatedClassNames(); final List classes = new ArrayList(); final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive; final Map> map = aggregatedArchive.getClassesMap(); for (Map.Entry> entry : map.entrySet()) { if (hasBeansXml(entry.getKey())) classes.addAll(entry.getValue()); } return classes; } public static boolean hasBeansXml(URL url) { if (url.getPath().endsWith("WEB-INF/classes/")) return true; if (url.getPath().endsWith("!/META-INF/beans.xml")) return true; try { final URLClassLoader loader = new URLClassLoader(new URL[]{ url } , new EmptyResourcesClassLoader()); String[] paths = { "META-INF/beans.xml", "WEB-INF/beans.xml", "/WEB-INF/beans.xml", "/META-INF/beans.xml", }; for (String path : paths) { if (loader.findResource(path) != null) return true; } } catch (Exception e) { } return false; } private String getEjbName(MessageDriven mdb, Class beanClass) { return (mdb.name().isEmpty() ? beanClass.getSimpleName() : mdb.name()); } private String getEjbName(Stateful stateful, Class beanClass) { return (stateful.name().isEmpty() ? beanClass.getSimpleName() : stateful.name()); } private String getEjbName(Stateless stateless, Class beanClass) { return (stateless.name().isEmpty() ? beanClass.getSimpleName() : stateless.name()); } private String getEjbName(Singleton singleton, Class beanClass) { return (singleton.name().isEmpty() ? beanClass.getSimpleName() : singleton.name()); } private String getEjbName(ManagedBean managed, Class beanClass) { return (managed.value().isEmpty() ? beanClass.getSimpleName() : managed.value()); } private boolean isValidEjbAnnotationUsage(Class annotationClass, Annotated> beanClass, String ejbName, EjbModule ejbModule) { List> annotations = new ArrayList(asList(Singleton.class, Stateless.class, Stateful.class, MessageDriven.class)); annotations.remove(annotationClass); boolean b = true; for (Class secondAnnotation : annotations) { Annotation annotation = beanClass.getAnnotation(secondAnnotation); if (annotation == null) continue; String secondEjbName = null; if (annotation instanceof Stateful) { secondEjbName = getEjbName((Stateful) annotation, beanClass.get()); } else if (annotation instanceof Stateless) { secondEjbName = getEjbName((Stateless) annotation, beanClass.get()); } else if (annotation instanceof Singleton) { secondEjbName = getEjbName((Singleton) annotation, beanClass.get()); } else if (annotation instanceof MessageDriven) { secondEjbName = getEjbName((MessageDriven) annotation, beanClass.get()); } if (ejbName.equals(secondEjbName)) { ejbModule.getValidation().fail(ejbName, "multiplyAnnotatedAsBean", annotationClass.getSimpleName(), secondAnnotation.getSimpleName(), ejbName, beanClass.get().getName()); } } // not a dynamic proxy implemented bean if (beanClass.getAnnotation(PersistenceContext.class) == null && beanClass.getAnnotation(Proxy.class) == null && beanClass.get().isInterface()) { ejbModule.getValidation().fail(ejbName, "interfaceAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } if (!beanClass.get().isInterface() && isAbstract(beanClass.get().getModifiers())) { ejbModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } return b; } } |
blob | long method | t | t | f | long method | blob | 0 | 5024 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/config/AnnotationDeployer.java/#L411-L1700 | 2 | 496 | 5024 | major |
| 2559 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14835 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2559 | 14835 | major |
| 1090 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9724 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 1 | 1090 | 9724 | minor |
| 915 | { "NO, I did not find any bad smell" : "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 8246 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 915 | 8246 | critical |
| 720 | {"answer": "YES I found bad smells", "detected_smells": ["3. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
blob | 3. long method | t | t | f | 3. long method | blob | 0 | 6830 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 720 | 6830 | minor |
| 1530 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
data class | long method | t | t | f | long method | data class | 0 | 11205 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 1 | 1530 | 11205 | major |
| 1989 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12678 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 1989 | 12678 | major |
| 2350 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Inefficient use of exception handling 4. Large class 5. Inconsistent indentation 6. Inappropriate indentation level 7. Lack of cohesion 8. Violation of Single Responsibility Principle 9. Dependency injection without proper interface decoupling 10. Magic number usage 11. Inconsistent naming convention 12. Lack of access modifiers in method declarations 13. Code duplication 14. Violation of Open-Closed Principle 15. Poor exception handling 16. Inappropriate variable and method scope 17. Mixing of business logic and utility methods 18. Confusing method naming 19. Unused variables and parameters 20. Use of null values instead of proper error-handling 21. Tight coupling between classes 22. Lack of comments and documentation 23. Use of nested if statements instead of abstraction 24. Excessive use of if/else statements 25. Nested loop structures 26. Unnecessary conditional checks 27. Hard-coded values 28. Use of static initializers 29. Mixing of different levels of abstraction 30. Violation of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | Long method2 Feature envy3 Inefficient use of exception handling4 Large class5 Inconsistent indentation6 Inappropriate indentation level7 Lack of cohesion8 Violation of Single Responsibility Principle9 Dependency injection without proper interface decoupling | t | f | f | . Long method2. Feature envy3. Inefficient use of exception handling4. Large class5. Inconsistent indentation6. Inappropriate indentation level7. Lack of cohesion8. Violation of Single Responsibility Principle9. Dependency injection without proper interface decoupling | blob | 0 | 14205 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 2 | 2350 | 14205 | minor |
| 3437 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6831 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 3437 | 6831 | minor |
| 2200 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13500 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 1 | 2200 | 13500 | minor |
| 1759 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | Long method | t | f | f | Long method | data class | 0 | 11885 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 1759 | 11885 | minor |
| 2445 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 14492 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 2445 | 14492 | critical |
| 346 | no NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | f | f | f | long method | 0 | 3525 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 346 | 3525 | minor | ||
| 393 | YES I found bad smells the bad smells are: 1.Duplicated Code 2.Magic Number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Duplicated Code2Magic Number | t | f | f | .Duplicated Code2.Magic Number | long method | 0 | 3969 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 2 | 393 | 3969 | major |
| 3452 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long Method\n2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PeriodFormatterData { final DataRecord dr; String localeName; // debug public static boolean trace = false; public PeriodFormatterData(String localeName, DataRecord dr) { this.dr = dr; this.localeName = localeName; if(localeName == null) { throw new NullPointerException("localename is null"); } // System.err.println("** localeName is " + localeName); if (dr == null) { // Thread.dumpStack(); throw new NullPointerException("data record is null"); } } // none - chinese (all forms the same) // plural - english, special form for 1 // dual - special form for 1 and 2 // paucal - russian, special form for 1, for 2-4 and n > 20 && n % 10 == 2-4 // rpt_dual_few - slovenian, special form for 1, 2, 3-4 and n as above // hebrew, dual plus singular form for years > 11 // arabic, dual, plus singular form for all terms > 10 /** * Return the pluralization format used by this locale. * @return the pluralization format */ public int pluralization() { return dr.pl; } /** * Return true if zeros are allowed in the display. * @return true if zeros should be allowed */ public boolean allowZero() { return dr.allowZero; } public boolean weeksAloneOnly() { return dr.weeksAloneOnly; } public int useMilliseconds() { return dr.useMilliseconds; } /** * Append the appropriate prefix to the string builder, depending on whether and * how a limit and direction are to be displayed. * * @param tl how and whether to display the time limit * @param td how and whether to display the time direction * @param sb the string builder to which to append the text * @return true if a following digit will require a digit prefix */ public boolean appendPrefix(int tl, int td, StringBuffer sb) { if (dr.scopeData != null) { int ix = tl * 3 + td; ScopeData sd = dr.scopeData[ix]; if (sd != null) { String prefix = sd.prefix; if (prefix != null) { sb.append(prefix); return sd.requiresDigitPrefix; } } } return false; } /** * Append the appropriate suffix to the string builder, depending on whether and * how a limit and direction are to be displayed. * * @param tl how and whether to display the time limit * @param td how and whether to display the time direction * @param sb the string builder to which to append the text */ public void appendSuffix(int tl, int td, StringBuffer sb) { if (dr.scopeData != null) { int ix = tl * 3 + td; ScopeData sd = dr.scopeData[ix]; if (sd != null) { String suffix = sd.suffix; if (suffix != null) { if (trace) { System.out.println("appendSuffix '" + suffix + "'"); } sb.append(suffix); } } } } /** * Append the count and unit to the string builder. * * @param unit the unit to append * @param count the count of units, * 1000 * @param cv the format to use for displaying the count * @param uv the format to use for displaying the unit * @param useCountSep if false, force no separator between count and unit * @param useDigitPrefix if true, use the digit prefix * @param multiple true if there are multiple units in this string * @param last true if this is the last unit * @param wasSkipped true if the unit(s) before this were skipped * @param sb the string builder to which to append the text * @return true if will require skip marker */ @SuppressWarnings("fallthrough") public boolean appendUnit(TimeUnit unit, int count, int cv, int uv, boolean useCountSep, boolean useDigitPrefix, boolean multiple, boolean last, boolean wasSkipped, StringBuffer sb) { int px = unit.ordinal(); boolean willRequireSkipMarker = false; if (dr.requiresSkipMarker != null && dr.requiresSkipMarker[px] && dr.skippedUnitMarker != null) { if (!wasSkipped && last) { sb.append(dr.skippedUnitMarker); } willRequireSkipMarker = true; } if (uv != EUnitVariant.PLURALIZED) { boolean useMedium = uv == EUnitVariant.MEDIUM; String[] names = useMedium ? dr.mediumNames : dr.shortNames; if (names == null || names[px] == null) { names = useMedium ? dr.shortNames : dr.mediumNames; } if (names != null && names[px] != null) { appendCount(unit, false, false, count, cv, useCountSep, names[px], last, sb); // omit suffix, ok? return false; // omit skip marker } } // check cv if (cv == ECountVariant.HALF_FRACTION && dr.halfSupport != null) { switch (dr.halfSupport[px]) { case EHalfSupport.YES: break; case EHalfSupport.ONE_PLUS: if (count > 1000) { break; } // else fall through to decimal case EHalfSupport.NO: { count = (count / 500) * 500; // round to 1/2 cv = ECountVariant.DECIMAL1; } break; } } String name = null; int form = computeForm(unit, count, cv, multiple && last); if (form == FORM_SINGULAR_SPELLED) { if (dr.singularNames == null) { form = FORM_SINGULAR; name = dr.pluralNames[px][form]; } else { name = dr.singularNames[px]; } } else if (form == FORM_SINGULAR_NO_OMIT) { name = dr.pluralNames[px][FORM_SINGULAR]; } else if (form == FORM_HALF_SPELLED) { name = dr.halfNames[px]; } else { try { name = dr.pluralNames[px][form]; } catch (NullPointerException e) { System.out.println("Null Pointer in PeriodFormatterData["+localeName+"].au px: " + px + " form: " + form + " pn: " + Arrays.toString(dr.pluralNames)); throw e; } } if (name == null) { form = FORM_PLURAL; name = dr.pluralNames[px][form]; } boolean omitCount = (form == FORM_SINGULAR_SPELLED || form == FORM_HALF_SPELLED) || (dr.omitSingularCount && form == FORM_SINGULAR) || (dr.omitDualCount && form == FORM_DUAL); int suffixIndex = appendCount(unit, omitCount, useDigitPrefix, count, cv, useCountSep, name, last, sb); if (last && suffixIndex >= 0) { String suffix = null; if (dr.rqdSuffixes != null && suffixIndex < dr.rqdSuffixes.length) { suffix = dr.rqdSuffixes[suffixIndex]; } if (suffix == null && dr.optSuffixes != null && suffixIndex < dr.optSuffixes.length) { suffix = dr.optSuffixes[suffixIndex]; } if (suffix != null) { sb.append(suffix); } } return willRequireSkipMarker; } /** * Append a count to the string builder. * * @param unit the unit * @param count the count * @param cv the format to use for displaying the count * @param useSep whether to use the count separator, if available * @param name the term name * @param last true if this is the last unit to be formatted * @param sb the string builder to which to append the text * @return index to use if might have required or optional suffix, or -1 if none required */ public int appendCount(TimeUnit unit, boolean omitCount, boolean useDigitPrefix, int count, int cv, boolean useSep, String name, boolean last, StringBuffer sb) { if (cv == ECountVariant.HALF_FRACTION && dr.halves == null) { cv = ECountVariant.INTEGER; } if (!omitCount && useDigitPrefix && dr.digitPrefix != null) { sb.append(dr.digitPrefix); } int index = unit.ordinal(); switch (cv) { case ECountVariant.INTEGER: { if (!omitCount) { appendInteger(count/1000, 1, 10, sb); } } break; case ECountVariant.INTEGER_CUSTOM: { int val = count / 1000; // only custom names we have for now if (unit == TimeUnit.MINUTE && (dr.fiveMinutes != null || dr.fifteenMinutes != null)) { if (val != 0 && val % 5 == 0) { if (dr.fifteenMinutes != null && (val == 15 || val == 45)) { val = val == 15 ? 1 : 3; if (!omitCount) appendInteger(val, 1, 10, sb); name = dr.fifteenMinutes; index = 8; // hack break; } if (dr.fiveMinutes != null) { val = val / 5; if (!omitCount) appendInteger(val, 1, 10, sb); name = dr.fiveMinutes; index = 9; // hack break; } } } if (!omitCount) appendInteger(val, 1, 10, sb); } break; case ECountVariant.HALF_FRACTION: { // 0, 1/2, 1, 1-1/2... int v = count / 500; if (v != 1) { if (!omitCount) appendCountValue(count, 1, 0, sb); } if ((v & 0x1) == 1) { // hack, using half name if (v == 1 && dr.halfNames != null && dr.halfNames[index] != null) { sb.append(name); return last ? index : -1; } int solox = v == 1 ? 0 : 1; if (dr.genders != null && dr.halves.length > 2) { if (dr.genders[index] == EGender.F) { solox += 2; } } int hp = dr.halfPlacements == null ? EHalfPlacement.PREFIX : dr.halfPlacements[solox & 0x1]; String half = dr.halves[solox]; String measure = dr.measures == null ? null : dr.measures[index]; switch (hp) { case EHalfPlacement.PREFIX: sb.append(half); break; case EHalfPlacement.AFTER_FIRST: { if (measure != null) { sb.append(measure); sb.append(half); if (useSep && !omitCount) { sb.append(dr.countSep); } sb.append(name); } else { // ignore sep completely sb.append(name); sb.append(half); return last ? index : -1; // might use suffix } } return -1; // exit early case EHalfPlacement.LAST: { if (measure != null) { sb.append(measure); } if (useSep && !omitCount) { sb.append(dr.countSep); } sb.append(name); sb.append(half); } return last ? index : -1; // might use suffix } } } break; default: { int decimals = 1; switch (cv) { case ECountVariant.DECIMAL2: decimals = 2; break; case ECountVariant.DECIMAL3: decimals = 3; break; default: break; } if (!omitCount) appendCountValue(count, 1, decimals, sb); } break; } if (!omitCount && useSep) { sb.append(dr.countSep); } if (!omitCount && dr.measures != null && index < dr.measures.length) { String measure = dr.measures[index]; if (measure != null) { sb.append(measure); } } sb.append(name); return last ? index : -1; } /** * Append a count value to the builder. * * @param count the count * @param integralDigits the number of integer digits to display * @param decimalDigits the number of decimal digits to display, <= 3 * @param sb the string builder to which to append the text */ public void appendCountValue(int count, int integralDigits, int decimalDigits, StringBuffer sb) { int ival = count / 1000; if (decimalDigits == 0) { appendInteger(ival, integralDigits, 10, sb); return; } if (dr.requiresDigitSeparator && sb.length() > 0) { sb.append(' '); } appendDigits(ival, integralDigits, 10, sb); int dval = count % 1000; if (decimalDigits == 1) { dval /= 100; } else if (decimalDigits == 2) { dval /= 10; } sb.append(dr.decimalSep); appendDigits(dval, decimalDigits, decimalDigits, sb); if (dr.requiresDigitSeparator) { sb.append(' '); } } public void appendInteger(int num, int mindigits, int maxdigits, StringBuffer sb) { if (dr.numberNames != null && num < dr.numberNames.length) { String name = dr.numberNames[num]; if (name != null) { sb.append(name); return; } } if (dr.requiresDigitSeparator && sb.length() > 0) { sb.append(' '); } switch (dr.numberSystem) { case ENumberSystem.DEFAULT: appendDigits(num, mindigits, maxdigits, sb); break; case ENumberSystem.CHINESE_TRADITIONAL: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.TRADITIONAL)); break; case ENumberSystem.CHINESE_SIMPLIFIED: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.SIMPLIFIED)); break; case ENumberSystem.KOREAN: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.KOREAN)); break; } if (dr.requiresDigitSeparator) { sb.append(' '); } } /** * Append digits to the string builder, using this.zero for '0' etc. * * @param num the integer to append * @param mindigits the minimum number of digits to append * @param maxdigits the maximum number of digits to append * @param sb the string builder to which to append the text */ public void appendDigits(long num, int mindigits, int maxdigits, StringBuffer sb) { char[] buf = new char[maxdigits]; int ix = maxdigits; while (ix > 0 && num > 0) { buf[--ix] = (char)(dr.zero + (num % 10)); num /= 10; } for (int e = maxdigits - mindigits; ix > e;) { buf[--ix] = dr.zero; } sb.append(buf, ix, maxdigits - ix); } /** * Append a marker for skipped units internal to a string. * @param sb the string builder to which to append the text */ public void appendSkippedUnit(StringBuffer sb) { if (dr.skippedUnitMarker != null) { sb.append(dr.skippedUnitMarker); } } /** * Append the appropriate separator between units * * @param unit the unit to which to append the separator * @param afterFirst true if this is the first unit formatted * @param beforeLast true if this is the next-to-last unit to be formatted * @param sb the string builder to which to append the text * @return true if a prefix will be required before a following unit */ public boolean appendUnitSeparator(TimeUnit unit, boolean longSep, boolean afterFirst, boolean beforeLast, StringBuffer sb) { // long seps // false, false "...b', '...d" // false, true "...', and 'c" // true, false - "a', '...c" // true, true - "a' and 'b" if ((longSep && dr.unitSep != null) || dr.shortUnitSep != null) { if (longSep && dr.unitSep != null) { int ix = (afterFirst ? 2 : 0) + (beforeLast ? 1 : 0); sb.append(dr.unitSep[ix]); return dr.unitSepRequiresDP != null && dr.unitSepRequiresDP[ix]; } sb.append(dr.shortUnitSep); // todo: investigate whether DP is required } return false; } private static final int FORM_PLURAL = 0, FORM_SINGULAR = 1, FORM_DUAL = 2, FORM_PAUCAL = 3, FORM_SINGULAR_SPELLED = 4, // following are not in the pluralization list FORM_SINGULAR_NO_OMIT = 5, // a hack FORM_HALF_SPELLED = 6; private int computeForm(TimeUnit unit, int count, int cv, boolean lastOfMultiple) { // first check if a particular form is forced by the countvariant. if // SO, just return that. otherwise convert the count to an integer // and use pluralization rules to determine which form to use. // careful, can't assume any forms but plural exist. if (trace) { System.err.println("pfd.cf unit: " + unit + " count: " + count + " cv: " + cv + " dr.pl: " + dr.pl); Thread.dumpStack(); } if (dr.pl == EPluralization.NONE) { return FORM_PLURAL; } // otherwise, assume we have at least a singular and plural form int val = count/1000; switch (cv) { case ECountVariant.INTEGER: case ECountVariant.INTEGER_CUSTOM: { // do more analysis based on floor of count } break; case ECountVariant.HALF_FRACTION: { switch (dr.fractionHandling) { case EFractionHandling.FPLURAL: return FORM_PLURAL; case EFractionHandling.FSINGULAR_PLURAL_ANDAHALF: case EFractionHandling.FSINGULAR_PLURAL: { // if half-floor is 1/2, use singular // else if half-floor is not integral, use plural // else do more analysis int v = count / 500; if (v == 1) { if (dr.halfNames != null && dr.halfNames[unit.ordinal()] != null) { return FORM_HALF_SPELLED; } return FORM_SINGULAR_NO_OMIT; } if ((v & 0x1) == 1) { if (dr.pl == EPluralization.ARABIC && v > 21) { // hack return FORM_SINGULAR_NO_OMIT; } if (v == 3 && dr.pl == EPluralization.PLURAL && dr.fractionHandling != EFractionHandling.FSINGULAR_PLURAL_ANDAHALF) { return FORM_PLURAL; } } // it will display like an integer, so do more analysis } break; case EFractionHandling.FPAUCAL: { int v = count / 500; if (v == 1 || v == 3) { return FORM_PAUCAL; } // else use integral form } break; default: throw new IllegalStateException(); } } break; default: { // for all decimals switch (dr.decimalHandling) { case EDecimalHandling.DPLURAL: break; case EDecimalHandling.DSINGULAR: return FORM_SINGULAR_NO_OMIT; case EDecimalHandling.DSINGULAR_SUBONE: if (count < 1000) { return FORM_SINGULAR_NO_OMIT; } break; case EDecimalHandling.DPAUCAL: if (dr.pl == EPluralization.PAUCAL) { return FORM_PAUCAL; } break; default: break; } return FORM_PLURAL; } } // select among pluralization forms if (trace && count == 0) { System.err.println("EZeroHandling = " + dr.zeroHandling); } if (count == 0 && dr.zeroHandling == EZeroHandling.ZSINGULAR) { return FORM_SINGULAR_SPELLED; } int form = FORM_PLURAL; switch(dr.pl) { case EPluralization.NONE: break; // never get here case EPluralization.PLURAL: { if (val == 1) { form = FORM_SINGULAR_SPELLED; // defaults to form_singular if no spelled forms } } break; case EPluralization.DUAL: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { form = FORM_SINGULAR; } } break; case EPluralization.PAUCAL: { int v = val; v = v % 100; if (v > 20) { v = v % 10; } if (v == 1) { form = FORM_SINGULAR; } else if (v > 1 && v < 5) { form = FORM_PAUCAL; } } break; /* case EPluralization.RPT_DUAL_FEW: { int v = val; if (v > 20) { v = v % 10; } if (v == 1) { form = FORM_SINGULAR; } else if (v == 2) { form = FORM_DUAL; } else if (v > 2 && v < 5) { form = FORM_PAUCAL; } } break; */ case EPluralization.HEBREW: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { if (lastOfMultiple) { form = FORM_SINGULAR_SPELLED; } else { form = FORM_SINGULAR; } } else if (unit == TimeUnit.YEAR && val > 11) { form = FORM_SINGULAR_NO_OMIT; } } break; case EPluralization.ARABIC: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { form = FORM_SINGULAR; } else if (val > 10) { form = FORM_SINGULAR_NO_OMIT; } } break; default: System.err.println("dr.pl is " + dr.pl); throw new IllegalStateException(); } return form; } } |
blob | \n1. long method\n2. data class | t | t | f | {"\\",n,1,.," ",l,o,n,g," ",m,e,t,h,o,d,"\\",n,2,.," ",d,a,t,a," ",c,l,a,s,s} | {"\\",n,1,.," ",o,n,g," ",m,t,h,o,d,"\\",n,2,.," ",d,t," ",c} | 0 | 6926 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/duration/impl/PeriodFormatterData.java/#L37-L676 | 1 | 3452 | 6926 | critical |
| 831 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 7738 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 1 | 831 | 7738 | critical |
| 2129 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 13225 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 1 | 2129 | 13225 | minor | ||
| 2352 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | long method | t | t | f | long method | data class | 0 | 14223 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2352 | 14223 | minor |
| 1921 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 12424 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 1921 | 12424 | minor |
| 3913 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10244 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 3913 | 10244 | minor |
| 1039 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TriplesOrQuadsReader extends AbstractRdfReader { @Override protected RecordReader selectRecordReader(Lang lang) throws IOException { if (!RDFLanguages.isQuads(lang) && !RDFLanguages.isTriples(lang)) throw new IOException(lang.getLabel() + " is not a RDF triples/quads format"); if (HadoopRdfIORegistry.hasQuadReader(lang)) { // Supports quads directly return HadoopRdfIORegistry.createQuadReader(lang); } else { // Try to create a triples reader and wrap upwards into quads // This will throw an error if a triple reader is not available return new TriplesToQuadsReader(HadoopRdfIORegistry.createTripleReader(lang)); } } /** * Gets the graph node which represents the graph into which triples will be * indicated to belong to when they are converting into quads. * * Defaults to {@link Quad#defaultGraphNodeGenerated} which represents the * default graph * * * @return Graph node */ protected Node getGraphNode() { return Quad.defaultGraphNodeGenerated; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9413 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-elephas/jena-elephas-io/src/main/java/org/apache/jena/hadoop/rdf/io/input/readers/TriplesOrQuadsReader.java/#L40-L70 | 2 | 1039 | 9413 | minor |
| 534 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 5480 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 534 | 5480 | major |
| 145 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Unused code", "Code duplication" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public abstract class AbstractEntitiesRuntimeModule extends DefaultXbaseRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/xtext/idea/example/entities/Entities.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.idea.example.entities.Entities"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("entities"); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class bindIGrammarAccess() { return EntitiesGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISemanticSequencer() { return EntitiesSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISyntacticSequencer() { return EntitiesSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIParser() { return EntitiesParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIAntlrTokenFileProvider() { return EntitiesAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindLexer() { return InternalEntitiesLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider provideInternalEntitiesLexer() { return LexerProvider.create(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class bindEntitiesValidator() { return EntitiesValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public Class bindIBatchScopeProvider() { return EntitiesScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIScopeProviderDelegate(Binder binder) { binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(XImportSectionNamespaceScopeProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIgnoreCaseLinking(Binder binder) { binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIContainer$Manager() { return StateBasedContainerManager.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIAllContainersState$Provider() { return ResourceSetBasedAllContainersStateProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptions(Binder binder) { binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptionsPersisted(Binder binder) { binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class bindIFormatter2() { return EntitiesFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIQualifiedNameProvider() { return XbaseQualifiedNameProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindILocationInFileProvider() { return JvmLocationInFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIGlobalScopeProvider() { return TypesAwareDefaultGlobalScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindFeatureNameValidator() { return LogicalContainerAwareFeatureNameValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultBatchTypeResolver() { return LogicalContainerAwareBatchTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultReentrantTypeResolver() { return LogicalContainerAwareReentrantTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIResourceValidator() { return DerivedStateAwareResourceValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIJvmModelInferrer() { return EntitiesJvmModelInferrer.class; } } |
blob | long method, unused code, code duplication | t | t | f | long method, unused code, code duplication | blob | 0 | 1809 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities/src-gen/org/eclipse/xtext/idea/example/entities/AbstractEntitiesRuntimeModule.java/#L76-L249 | 2 | 145 | 1809 | minor |
| 694 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 6656 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 1 | 694 | 6656 | minor |
| 1228 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10354 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1228 | 10354 | minor |
| 841 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_LOCATION = 1; private static final String NEARBY_BEACONS_FRAGMENT_TAG = "NearbyBeaconsFragmentTag"; private static final String SETTINGS_FRAGMENT_TAG = "SettingsFragmentTag"; private static final String BLOCKED_URLS_FRAGMENT_TAG = "BlockedUrlsFragmentTag"; private static final String ABOUT_FRAGMENT_TAG = "AboutFragmentTag"; private static final String DEMOS_FRAGMENT_TAG = "DemosFragmentTag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Utils.setSharedPreferencesDefaultValues(this); PermissionCheck.getInstance().setCheckingPermissions(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * Called when a menu item is tapped. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // If the about menu item was selected case R.id.action_about: showAboutFragment(); return true; // If the settings menu item was selected case R.id.action_settings: showSettingsFragment(); return true; case R.id.block_settings: showBlockedFragment(); return true; case R.id.action_demos: showDemosFragment(); return true; // If the action bar up button was pressed case android.R.id.home: getFragmentManager().popBackStack(); getActionBar().setDisplayHomeAsUpEnabled(false); } return super.onOptionsItemSelected(item); } /** * Ensures Bluetooth is available on the beacon and it is enabled. If not, * displays a dialog requesting user permission to enable Bluetooth. */ private void checkPermissions(BluetoothAdapter bluetoothAdapter) { // Acquire lock PermissionCheck.getInstance().setCheckingPermissions(true); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } ensureLocationPermissionIsEnabled(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == REQUEST_ENABLE_BT && resultCode == -1) { ensureLocationPermissionIsEnabled(); return; } Toast.makeText(this, getString(R.string.bt_on), Toast.LENGTH_LONG).show(); finish(); } private void ensureLocationPermissionIsEnabled() { if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } PermissionCheck.getInstance().setCheckingPermissions(false); finishLoad(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionCheck.getInstance().setCheckingPermissions(false); } else { Toast.makeText(getApplicationContext(), getString(R.string.loc_permission), Toast.LENGTH_LONG).show(); finish(); } break; } default: } } @Override protected void onResume() { super.onResume(); // Lock to prevent onResume from running until all permissions are granted if (!PermissionCheck.getInstance().isCheckingPermissions()) { Log.d(TAG, "resumed MainActivity"); BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = btManager != null ? btManager.getAdapter() : null; if (btAdapter == null) { Toast.makeText(getApplicationContext(), R.string.error_bluetooth_support, Toast.LENGTH_LONG).show(); finish(); return; } if (Utils.checkIfUserHasOptedIn(this)) { Log.d(TAG, "checkingPermissions"); checkPermissions(btAdapter); } else { // Show the oob activity Intent intent = new Intent(this, OobActivity.class); startActivity(intent); } } } private void finishLoad() { Intent intent = new Intent(this, ScreenListenerService.class); startService(intent); NearbyBeaconsFragment nearbyBeaconsFragment = (NearbyBeaconsFragment) getFragmentManager().findFragmentByTag(NEARBY_BEACONS_FRAGMENT_TAG); if (nearbyBeaconsFragment != null) { nearbyBeaconsFragment.restartScan(); } else { showFragment(new NearbyBeaconsFragment(), NEARBY_BEACONS_FRAGMENT_TAG, false); } } /** * Show the fragment to configure the app. */ private void showSettingsFragment() { showFragment(new SettingsFragment(), SETTINGS_FRAGMENT_TAG, true); } /** * Show the fragment displaying information about this application. */ private void showAboutFragment() { showFragment(new AboutFragment(), ABOUT_FRAGMENT_TAG, true); } /** * Show the fragment displaying the blocked URLs. */ private void showBlockedFragment() { showFragment(new BlockedFragment(), BLOCKED_URLS_FRAGMENT_TAG, true); } /** * Show the fragment displaying the demos. */ private void showDemosFragment() { showFragment(new DemosFragment(), DEMOS_FRAGMENT_TAG, true); } @SuppressLint("CommitTransaction") private void showFragment(Fragment newFragment, String fragmentTag, boolean addToBackStack) { FragmentTransaction transaction = getFragmentManager().beginTransaction() .setCustomAnimations( R.animator.fade_in_and_slide_up_fragment, R.animator.fade_out_fragment, R.animator.fade_in_activity, R.animator.fade_out_fragment) .replace(R.id.main_activity_container, newFragment, fragmentTag); if (addToBackStack) { transaction.addToBackStack(null); } transaction.commit(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 7797 | https://github.com/google/physical-web/blob/12604319e99b6d6dff451fc5a58a13a271f1dc7a/android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/MainActivity.java/#L39-L228 | 1 | 841 | 7797 | major |
| 2385 | YES I found bad smells Long method Feature envy (the methods in this class are mostly delegating to other methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | t | f | f | blob | 0 | 14347 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 2 | 2385 | 14347 | major | ||
| 59 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Not specified | f | f | f | false | 0 | 1004 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 59 | 1004 | critical | |
| 1123 | YES I found bad smells The bad smells are: 1. Empty default constructor 2. Mutable fields (incomplete and items) 3. Getters and setters for every field, violating encapsulation principle 4. Poor naming of class and fields, not following camelCase naming convention 5. Lack of comments and documentation 6. No methods or functionality defined in the class, rendering it useless | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Empty default constructor2 Mutable fields (incomplete and items)3 Getters and setters for every field, violating encapsulation principle4 Poor naming of class and fields, not following camelCase naming convention5 Lack of comments and documentation6 No methods or functionality defined in the class, rendering it useless | t | f | f | . Empty default constructor2. Mutable fields (incomplete and items)3. Getters and setters for every field, violating encapsulation principle4. Poor naming of class and fields, not following camelCase naming convention5. Lack of comments and documentation6. No methods or functionality defined in the class, rendering it useless | data class | 0 | 9994 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 1123 | 9994 | critical |
| 2106 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 13171 | https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/.mvn/wrapper/MavenWrapperDownloader.java/#L25-L110 | 2 | 2106 | 13171 | minor |
| 386 | { "NO, I did not find any bad smell" : "YES, I found bad smells", "the bad smells are": [ "Long Method", "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
blob | "YES, I found bad smells", "the bad smells are" | t | f | f | "YES, I found bad smells", "the bad smells are" | blob | 0 | 3940 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 386 | 3940 | major |
| 432 | { "answer": "YES I found bad smells", "bad smells are": ["1. Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class InvalidStateTransitionException extends Exception { private Enum currentState; private Enum event; public InvalidStateTransitionException(Enum currentState, Enum event) { super("Invalid event: " + event + " at " + currentState); this.currentState = currentState; this.event = event; } public Enum getCurrentState() { return currentState; } public Enum getEvent() { return event; } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 4281 | https://github.com/apache/incubator-ambari/blob/bf747346312170834c6beb89a60c8624b47aa288/ambari-server/src/main/java/org/apache/ambari/server/state/fsm/InvalidStateTransitionException.java/#L25-L45 | 1 | 432 | 4281 | critical |
| 1726 | {"response": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CoordActionQueryExecutor extends QueryExecutor { public enum CoordActionQuery { UPDATE_COORD_ACTION, UPDATE_COORD_ACTION_STATUS_PENDING_TIME, UPDATE_COORD_ACTION_FOR_INPUTCHECK, UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK, UPDATE_COORD_ACTION_DEPENDENCIES, UPDATE_COORD_ACTION_FOR_START, UPDATE_COORD_ACTION_FOR_MODIFIED_DATE, UPDATE_COORD_ACTION_RERUN, GET_COORD_ACTION, GET_COORD_ACTION_STATUS, GET_COORD_ACTIVE_ACTIONS_COUNT_BY_JOBID, GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME, GET_COORD_ACTIONS_STATUS_UNIGNORED, GET_COORD_ACTIONS_PENDING_COUNT, GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE, GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE, GET_TERMINATED_ACTIONS_FOR_DATES, GET_TERMINATED_ACTION_IDS_FOR_DATES, GET_ACTIVE_ACTIONS_FOR_DATES, GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN, GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN, GET_COORD_ACTION_FOR_SLA, GET_COORD_ACTION_FOR_INPUTCHECK }; private static CoordActionQueryExecutor instance = new CoordActionQueryExecutor(); private CoordActionQueryExecutor() { } public static QueryExecutor getInstance() { return CoordActionQueryExecutor.instance; } @Override public Query getUpdateQuery(CoordActionQuery namedQuery, CoordinatorActionBean actionBean, EntityManager em) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); switch (namedQuery) { case UPDATE_COORD_ACTION: query.setParameter("actionNumber", actionBean.getActionNumber()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("consoleUrl", actionBean.getConsoleUrl()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("timeOut", actionBean.getTimeOut()); query.setParameter("trackerUri", actionBean.getTrackerUri()); query.setParameter("type", actionBean.getType()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("jobId", actionBean.getJobId()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("nominalTime", actionBean.getNominalTimestamp()); query.setParameter("slaXml", actionBean.getSlaXmlBlob()); query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_STATUS_PENDING_TIME: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("pending", actionBean.getPending()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_DEPENDENCIES: query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_START: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("pending", actionBean.getPending()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_MODIFIED_DATE: query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_RERUN: query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("status", actionBean.getStatusStr()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("rerunTime", actionBean.getRerunTimestamp()); query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + namedQuery.name()); } return query; } @Override public Query getSelectQuery(CoordActionQuery namedQuery, EntityManager em, Object... parameters) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); CoordActionQuery caQuery = (CoordActionQuery) namedQuery; switch (caQuery) { case GET_COORD_ACTION: case GET_COORD_ACTION_STATUS: case GET_COORD_ACTION_FOR_SLA: case GET_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("id", parameters[0]); break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: query.setParameter("jobId", parameters[0]); break; case GET_COORD_ACTIONS_PENDING_COUNT: query.setParameter("jobId", parameters[0]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: query.setParameter("ids", parameters[0]); break; case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: query.setParameter("jobId", parameters[0]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: case GET_TERMINATED_ACTION_IDS_FOR_DATES: case GET_ACTIVE_ACTIONS_FOR_DATES: query.setParameter("jobId", parameters[0]); query.setParameter("startTime", new Timestamp(((Date) parameters[1]).getTime())); query.setParameter("endTime", new Timestamp(((Date) parameters[2]).getTime())); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); query.setParameter("currentTime", new Timestamp(new Date().getTime())); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + caQuery.name()); } return query; } @Override public int executeUpdate(CoordActionQuery namedQuery, CoordinatorActionBean jobBean) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getUpdateQuery(namedQuery, jobBean, em); int ret = jpaService.executeUpdate(namedQuery.name(), query, em); return ret; } @Override public CoordinatorActionBean get(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { CoordinatorActionBean bean = getIfExist(namedQuery, parameters); if (bean == null) { throw new JPAExecutorException(ErrorCode.E0605, getSelectQuery(namedQuery, Services.get().get(JPAService.class).getEntityManager(), parameters).toString()); } return bean; } @Override public CoordinatorActionBean getIfExist(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { return null; } CoordinatorActionBean bean = constructBean(namedQuery, ret); return bean; } @Override public List getList(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); List retList = (List) jpaService.executeGetList(namedQuery.name(), query, em); List beanList = new ArrayList(); if (retList != null) { for (Object ret : retList) { beanList.add(constructBean(namedQuery, ret)); } } return beanList; } private CoordinatorActionBean constructBean(CoordActionQuery namedQuery, Object ret) throws JPAExecutorException { CoordinatorActionBean bean; Object[] arr; switch (namedQuery) { case GET_COORD_ACTION: bean = (CoordinatorActionBean) ret; break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: bean = new CoordinatorActionBean(); bean.setJobId((String) ret); break; case GET_COORD_ACTION_STATUS: bean = new CoordinatorActionBean(); bean.setStatusStr((String)ret); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setStatusStr((String)arr[0]); bean.setPending((Integer)arr[1]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setNominalTime((Timestamp)arr[1]); bean.setCreatedTime((Timestamp)arr[2]); bean.setActionXmlBlob((StringBlob)arr[3]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: bean = (CoordinatorActionBean) ret; break; case GET_TERMINATED_ACTION_IDS_FOR_DATES: bean = new CoordinatorActionBean(); bean.setId((String) ret); break; case GET_ACTIVE_ACTIONS_FOR_DATES: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); bean.setNominalTime((Timestamp) arr[5]); bean.setCreatedTime((Timestamp) arr[6]); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPushMissingDependenciesBlob((StringBlob) arr[4]); break; case GET_COORD_ACTION_FOR_SLA: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setJobId((String) arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setLastModifiedTime((Timestamp) arr[4]); break; case GET_COORD_ACTION_FOR_INPUTCHECK: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setActionNumber((Integer) arr[1]); bean.setJobId((String) arr[2]); bean.setStatus(CoordinatorAction.Status.valueOf((String) arr[3])); bean.setRunConfBlob((StringBlob) arr[4]); bean.setNominalTime(DateUtils.toDate((Timestamp) arr[5])); bean.setCreatedTime(DateUtils.toDate((Timestamp) arr[6])); bean.setActionXmlBlob((StringBlob) arr[7]); bean.setMissingDependenciesBlob((StringBlob) arr[8]); bean.setPushMissingDependenciesBlob((StringBlob) arr[9]); bean.setTimeOut((Integer) arr[10]); bean.setExternalId((String) arr[11]); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot construct action bean for " + namedQuery.name()); } return bean; } @Override public Object getSingleValue(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { throw new JPAExecutorException(ErrorCode.E0604, query.toString()); } return ret; } } |
blob | data class | t | t | f | data class | blob | 0 | 11808 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/executor/jpa/CoordActionQueryExecutor.java/#L40-L383 | 1 | 1726 | 11808 | major |
| 2506 | YES, I found bad smells the bad smells are: 1. Getter and setter methods present for a single variable, which can indicate feature envy 2. Lack of readability due to inconsistent indentation 3. The class name and variable name do not follow Java naming conventions 4. The class is declared as static, which may not be necessary 5. Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Getter and setter methods present for a single variable, which can indicate feature envy2 Lack of readability due to inconsistent indentation3 The class name and variable name do not follow Java naming conventions 4 The class is declared as static, which may not be necessary 5 Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems | t | f | f | . Getter and setter methods present for a single variable, which can indicate feature envy2. Lack of readability due to inconsistent indentation3. The class name and variable name do not follow Java naming conventions 4. The class is declared as static, which may not be necessary 5. Use of a single String variable for an email could potentially lead to issues with validation or formatting in more complex systems. | data class | 0 | 14669 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 2506 | 14669 | major |
| 5040 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14066 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 | 1 | 5040 | 14066 | minor |
| 3634 | { "message": "YES I found bad smells", "detected_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ImmediatelyThrowsEvent makeImmediatelyThrowsEvent(final int processId, final int invokeId, final Throwable throwable) { if (null == immediatelyThrowsEvent) { immediatelyThrowsEvent = new ImmediatelyThrowsEvent(ILLEGAL_PROCESS_ID, ILLEGAL_INVOKE_ID, null); } unsafe.putInt(immediatelyThrowsEvent, processIdFieldInInvokeEventOffset, processId); unsafe.putInt(immediatelyThrowsEvent, invokeIdFieldInInvokeEventOffset, invokeId); unsafe.putObject(immediatelyThrowsEvent, throwableFieldInThrowsEventOffset, throwable); return immediatelyThrowsEvent; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8213 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/enhance/weaver/SingleEventFactory.java/#L130-L140 | 1 | 3634 | 8213 | minor |
| 906 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Shotgun surgery 4. Magic numbers 5. Inappropriate names 6. Data clumps 7. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } } |
blob | Long method2 Feature envy3 Shotgun surgery4 Magic numbers5 Inappropriate names6 Data clumps7 Duplicate code | t | f | f | . Long method2. Feature envy3. Shotgun surgery4. Magic numbers5. Inappropriate names6. Data clumps7. Duplicate code | blob | 0 | 8195 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 | 2 | 906 | 8195 | minor |
| 2123 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 13215 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 1 | 2123 | 13215 | major |
| 113 | {"response": "YES I found bad smells", "identified_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Value @Wither(AccessLevel.PACKAGE) class CollectionJson { private String version; private @Nullable String href; private @JsonInclude(Include.NON_EMPTY) Links links; private @JsonInclude(Include.NON_EMPTY) List> items; private @JsonInclude(Include.NON_EMPTY) List queries; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonTemplate template; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonError error; @JsonCreator CollectionJson(@JsonProperty("version") String version, // @JsonProperty("href") @Nullable String href, // @JsonProperty("links") @Nullable Links links, // @JsonProperty("items") @Nullable List> items, // @JsonProperty("queries") @Nullable List queries, // @JsonProperty("template") @Nullable CollectionJsonTemplate template, // @JsonProperty("error") @Nullable CollectionJsonError error) { this.version = version; this.href = href; this.links = links == null ? Links.NONE : links; this.items = items == null ? Collections.emptyList() : items; this.queries = queries == null ? Collections.emptyList() : queries; this.template = template; this.error = error; } CollectionJson() { this("1.0", null, Links.NONE, Collections.emptyList(), null, null, null); } @SafeVarargs final CollectionJson withItems(CollectionJsonItem... items) { return withItems(Arrays.asList(items)); } CollectionJson withItems(List> items) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withLinks(Link... links) { return withLinks(Links.of(links)); } CollectionJson withLinks(Links links) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withOwnSelfLink() { String href = this.href; if (href == null) { return this; } return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links)); } boolean hasItems() { return !items.isEmpty(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 1473 | https://github.com/spring-projects/spring-hateoas/blob/0e02d4f04117e03ab94110c9de09b2ac28d55599/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java/#L41-L107 | 1 | 113 | 1473 | minor |
| 2234 | YES I found bad smells, the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | Long method | t | f | f | . Long method | blob | 0 | 13604 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 2 | 2234 | 13604 | minor |
| 1884 | { "output": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12292 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 1884 | 12292 | minor |
| 443 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 4309 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 443 | 4309 | critical |
| 843 | { "message": "YES I found bad smells", "the bad smells are:": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | "YES I found bad smells", "the bad smells are | t | f | f | "YES I found bad smells", "the bad smells are | blob | 0 | 7804 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 1 | 843 | 7804 | critical |
| 704 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class N4JSNewProjectWizard extends XtextNewProjectWizard { private static final ImageDescriptor NEW_PROJECT_WIZBAN_DESC = ImageRef.NEW_PROJECT_WIZBAN.asImageDescriptor() .orNull(); private static final String DIALOG_SETTINGS_SECTION_KEY = "org.eclipse.n4js.ui.wizard.project.N4JSNewProjectWizard.dialogSettings"; private static final String CREATE_GREETER_SETTINGS_KEY = "createGreeterFile"; private static final String VENDOR_ID_SETTINGS_KEY = "vendorId"; private final N4JSProjectInfo projectInfo; @Inject private IResourceDescriptions resourceDescriptions; private N4JSNewProjectWizardCreationPage newProjectWizardCreationPage; /** * Creates a new wizard container for creating and initializing a new N4JS project into the workspace. * * @param projectCreator * the project creation logic to be triggered when finishing this wizard. */ @Inject public N4JSNewProjectWizard(final IProjectCreator projectCreator) { super(projectCreator); setWindowTitle("New N4JS Project"); setNeedsProgressMonitor(true); setDefaultPageImageDescriptor(NEW_PROJECT_WIZBAN_DESC); projectInfo = new N4JSProjectInfo(); // Setup the dialog settings IDialogSettings workbenchDialogSettings = N4JSActivator.getInstance().getDialogSettings(); IDialogSettings projectWizardSettings = workbenchDialogSettings.getSection(DIALOG_SETTINGS_SECTION_KEY); if (null == projectWizardSettings) { projectWizardSettings = workbenchDialogSettings.addNewSection(DIALOG_SETTINGS_SECTION_KEY); } setDialogSettings(projectWizardSettings); } @Override public void createPageControls(Composite pageContainer) { super.createPageControls(pageContainer); IDialogSettings dialogSettings = this.getDialogSettings(); if (null != dialogSettings.get(CREATE_GREETER_SETTINGS_KEY)) { projectInfo.setCreateGreeterFile(dialogSettings.getBoolean(CREATE_GREETER_SETTINGS_KEY)); } if (null != dialogSettings.get(VENDOR_ID_SETTINGS_KEY)) { projectInfo.setVendorId(dialogSettings.get(VENDOR_ID_SETTINGS_KEY)); } } @Override public void addPages() { newProjectWizardCreationPage = new N4JSNewProjectWizardCreationPage(projectInfo); addPage(newProjectWizardCreationPage); addPage(new N4JSTestedProjectWizardPage(projectInfo, resourceDescriptions)); } @Override public boolean performFinish() { // Save the value for the create greeter file checkbox and the vendor id this.getDialogSettings().put(CREATE_GREETER_SETTINGS_KEY, projectInfo.getCreateGreeterFile()); this.getDialogSettings().put(VENDOR_ID_SETTINGS_KEY, projectInfo.getVendorId()); return super.performFinish(); } @Override public boolean canFinish() { /* * Can finish after first page for non-test projects or like normally if all pages are complete for test * projects * * This means that even for test projects the whole second page can be completely skipped. */ return (!ProjectType.TEST.equals(projectInfo.getProjectType()) && newProjectWizardCreationPage.isPageComplete()) || super.canFinish(); } @Override protected IProjectInfo getProjectInfo() { // update workingsets: newProjectWizardCreationPage.updateSelectedWorkingSets(); return projectInfo; } } |
blob | long method | t | t | f | long method | blob | 0 | 6704 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/wizard/project/N4JSNewProjectWizard.java/#L31-L119 | 1 | 704 | 6704 | minor |
| 4699 | { "answer": "YES I found bad smells", "the bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JpaEntityFactoryMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String INDEX_VAR = "index"; private static final JavaSymbolName INDEX_SYMBOL = new JavaSymbolName(INDEX_VAR); private static final JavaSymbolName MAX_SYMBOL = new JavaSymbolName("max"); private static final JavaSymbolName MIN_SYMBOL = new JavaSymbolName("min"); private static final String OBJ_VAR = "obj"; private static final JavaSymbolName OBJ_SYMBOL = new JavaSymbolName(OBJ_VAR); private static final JavaSymbolName VALUE = new JavaSymbolName("value"); private static final JavaSymbolName CREATE_FACTORY_METHOD_NAME = new JavaSymbolName("create"); public static final JavaSymbolName SPECIFIC_METHOD_PREFIX = new JavaSymbolName("getSpecific"); private static final String PROVIDES_TYPE_STRING = JpaEntityFactoryMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); public static String createIdentifier(final JavaType javaType, final LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static String createIdentifier(ClassOrInterfaceTypeDetails details) { final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(details.getDeclaredByMetadataId()); return createIdentifier(details.getType(), logicalPath); } public static JavaType getJavaType(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static LogicalPath getPath(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private JavaType entity; private final List requiredDataOnDemandCollaborators = new ArrayList(); private MethodMetadata randomPersistentEntityMethod; private final Map> embeddedFieldInitializers = new LinkedHashMap>(); private final Map fieldInitializers = new LinkedHashMap(); private EmbeddedIdHolder embeddedIdHolder; private List embeddedHolders; private Map locatedFields; private final MemberDetails entityMemberDetails; /** * Constructor * * @param identifier * @param aspectName * @param governorPhysicalTypeMetadata * @param entity * @param entityMemberDetails * @param locatedFields * @param embeddedHolder * @param entityFactoryClasses * @param embeddedIdHolder */ public JpaEntityFactoryMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JavaType entity, MemberDetails entityMemberDetails, final Map locatedFields, final List embeddedHolders, Set entityFactoryClasses, final EmbeddedIdHolder embeddedIdHolder) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.notNull(locatedFields, "Located fields map required"); Validate.notNull(embeddedHolders, "Embedded holders list required"); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.embeddedIdHolder = embeddedIdHolder; this.embeddedHolders = embeddedHolders; this.locatedFields = locatedFields; builder.addMethod(getCreateMethod()); // Calculate and store field initializers for (final Map.Entry entry : locatedFields.entrySet()) { final FieldMetadata field = entry.getKey(); final String initializer = getFieldInitializer(field, entry.getValue(), entityFactoryClasses); if (!StringUtils.isBlank(initializer)) { this.fieldInitializers.put(field, initializer); } } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { final Map initializers = new LinkedHashMap(); for (final FieldMetadata field : embeddedHolder.getFields()) { initializers.put(field, getFieldInitializer(field, null, entityFactoryClasses)); } this.embeddedFieldInitializers.put(embeddedHolder.getEmbeddedField(), initializers); } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { builder.addMethod(getEmbeddedClassMutatorMethod(embeddedHolder)); addEmbeddedClassFieldMutatorMethodsToBuilder(embeddedHolder, entityFactoryClasses); } for (final MethodMetadataBuilder fieldInitializerMethod : getFieldMutatorMethods()) { builder.addMethod(fieldInitializerMethod); } addCollaboratingFieldsToBuilder(entityFactoryClasses); builder.addMethod(getEmbeddedIdMutatorMethod(entityFactoryClasses)); itdTypeDetails = builder.build(); } private void addCollaboratingFieldsToBuilder( final Set entityFactoryClasses) { final Set fields = new LinkedHashSet(); for (final JavaType entityNeedingCollaborator : this.requiredDataOnDemandCollaborators) { final JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator, entityFactoryClasses); if (collaboratorType != null) { final String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator, entityFactoryClasses) .getSymbolName(); final JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // We really expect the field to be correct if we're going to // rely on it Validate .isTrue(candidate.getFieldType().equals(collaboratorType), "Field '%s' on '%s' must be of type '%s'", collaboratingFieldName, destination.getFullyQualifiedTypeName(), collaboratorType.getFullyQualifiedTypeName()); Validate.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '%s' on '%s' must be private", collaboratingFieldName, destination.getFullyQualifiedTypeName()); Validate.notNull( MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), AUTOWIRED), "Field '%s' on '%s' must be @Autowired", collaboratingFieldName, destination.getFullyQualifiedTypeName()); // It's ok, so we can move onto the new field continue; } // Create field and add it to the ITD, if it hasn't already been if (!fields.contains(fieldSymbolName)) { // Must make the field final List annotations = new ArrayList(); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); builder.addField(new FieldMetadataBuilder(getId(), 0, annotations, fieldSymbolName, collaboratorType)); fields.add(fieldSymbolName); } } } } private void addEmbeddedClassFieldMutatorMethodsToBuilder(final EmbeddedHolder embeddedHolder, final Set dataOnDemandClasses) { final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); final JavaType[] parameterTypes = {embeddedFieldType, JavaType.INT_PRIMITIVE}; final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); for (final FieldMetadata field : embeddedHolder.getFields()) { final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); final JavaSymbolName fieldMutatorMethodName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, fieldMutatorMethodName, false)); final JavaSymbolName embeddedClassMethodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()); if (governorHasMethod(embeddedClassMethodName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } builder.addMethod(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, embeddedClassMethodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType .convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } private String getColumnPrecisionAndScaleBody(final FieldMetadata field, final Map values, final String suffix) { if (values == null || !values.containsKey("precision")) { return InvocableMemberBodyBuilder.getInstance().getOutput(); } final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); Integer precision = (Integer) values.get("precision"); Integer scale = (Integer) values.get("scale"); if (precision != null && scale != null && precision < scale) { scale = 0; } final BigDecimal maxValue; if (scale == null || scale == 0) { maxValue = new BigDecimal(StringUtils.rightPad("9", precision, '9')); } else { maxValue = new BigDecimal(StringUtils.rightPad("9", precision - scale, '9') + "." + StringUtils.rightPad("9", scale, '9')); } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private JavaSymbolName getCollaboratingFieldName(final JavaType entity, final Set dataOnDemandClasses) { JavaSymbolName symbolName = null; JavaType collaboratingType = getCollaboratingType(entity, dataOnDemandClasses); if (collaboratingType != null) { symbolName = new JavaSymbolName(StringUtils.uncapitalize(collaboratingType.getSimpleTypeName())); } return symbolName; } private JavaType getCollaboratingType(final JavaType entity, final Set entityFactoryClasses) { JavaType dataOnDemand = null; for (ClassOrInterfaceTypeDetails dataOnDemandClass : entityFactoryClasses) { String searchDataOnDemand = entity.getSimpleTypeName().concat("DataOnDemand"); if (dataOnDemandClass.getType().getSimpleTypeName().equals(searchDataOnDemand) && governorTypeDetails.getType().getModule() .equals(dataOnDemandClass.getType().getModule())) { dataOnDemand = dataOnDemandClass.getType(); } } return dataOnDemand; } private MethodMetadata getCreateMethod() { // Define methodName final JavaSymbolName methodName = CREATE_FACTORY_METHOD_NAME; List parameterTypes = new ArrayList(); parameterTypes.add(JavaType.INT_PRIMITIVE); // Check if method exists MethodMetadata existingMethod = getGovernorMethod(methodName, parameterTypes); if (existingMethod != null) { return existingMethod; } List parameterNames = new ArrayList(); parameterNames.add(INDEX_SYMBOL); // Add body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); List constructors = entityMemberDetails.getConstructors(); boolean hasDefaultConstructor = false; for (ConstructorMetadata constructor : constructors) { if (constructor.getParameterTypes().isEmpty() && Modifier.isPublic(constructor.getModifier())) { hasDefaultConstructor = true; break; } } if (constructors.isEmpty() || hasDefaultConstructor) { generateDefaultCreateMethodBody(bodyBuilder); } else { generateNoConstructorCreateMethodBody(bodyBuilder); } // Create method MethodMetadataBuilder method = new MethodMetadataBuilder(this.getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); CommentStructure commentStructure = new CommentStructure(); List paramsInfo = new ArrayList(); paramsInfo.add(String.format("%s position of the %s", INDEX_VAR, this.entity.getSimpleTypeName())); JavadocComment comment = new JavadocComment(String.format("Creates a new {@link %s} with the given %s.", this.entity.getSimpleTypeName(), INDEX_VAR), paramsInfo, String.format( "a new transient %s", this.entity.getSimpleTypeName()), null); commentStructure.addComment(comment, CommentLocation.BEGINNING); method.setCommentStructure(commentStructure); return method.build(); } /** * Generate default body for create method * * @param bodyBuilder */ private void generateDefaultCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // Entity obj = new Entity(); bodyBuilder.appendFormalLine("%1$s %2$s = new %1$s();", getNameOfJavaType(this.entity), OBJ_SYMBOL); // Set values for transient object for (final Map.Entry entry : locatedFields.entrySet()) { bodyBuilder.appendFormalLine("%s(%s, %s);", BeanInfoUtils.getMutatorMethodName(entry.getKey()), OBJ_SYMBOL, INDEX_SYMBOL); } // return obj; bodyBuilder.appendFormalLine("return %s;", OBJ_SYMBOL); } /** * Generate body for create method when entity has not default constructor available * * @param bodyBuilder */ private void generateNoConstructorCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // throw new IllegalStateException("No no-argument constructor found for the entity "+ Pet.class.getName() +". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again."); bodyBuilder .appendFormalLine( "throw new IllegalStateException(\"No no-argument constructor found for the entity \"+ %s.class.getName() +\". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again.\");", getNameOfJavaType(this.entity)); } private String getDecimalMinAndDecimalMaxBody(final FieldMetadata field, final AnnotationMetadata decimalMinAnnotation, final AnnotationMetadata decimalMaxAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (decimalMinAnnotation != null && decimalMaxAnnotation == null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation == null && decimalMaxAnnotation != null) { final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation != null && decimalMaxAnnotation != null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue( Double.parseDouble(maxValue) >= Double.parseDouble(minValue), "The value of @DecimalMax must be greater or equal to the value of @DecimalMin for field %s", fieldName); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getDigitsBody(final FieldMetadata field, final AnnotationMetadata digitsAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final Integer integerValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("integer")).getValue(); final Integer fractionValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("fraction")).getValue(); final BigDecimal maxValue = new BigDecimal(StringUtils.rightPad("9", integerValue, '9') + "." + StringUtils.rightPad("9", fractionValue, '9')); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private String getFieldInitializer(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set dataOnDemandClasses) { final JavaType fieldType = field.getFieldType(); final String fieldName = field.getFieldName().getSymbolName(); String initializer = "null"; final String fieldInitializer = field.getFieldInitializer(); final Set fieldCustomDataKeys = field.getCustomData().keySet(); // Date fields included for DataNucleus ( if (fieldType.equals(DATE)) { if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() - 10000000L)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() + 10000000L)"; } else { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); initializer = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime()"; } } else if (fieldType.equals(CALENDAR)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); final String calendarString = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH)"; if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { initializer = calendarString + " - 1)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { initializer = calendarString + " + 1)"; } else { initializer = "Calendar.getInstance()"; } } else if (fieldType.equals(TIMESTAMP)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR, TIMESTAMP); initializer = "new Timestamp(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime().getTime())"; } else if (fieldType.equals(STRING)) { if (fieldInitializer != null && fieldInitializer.contains("\"")) { final int offset = fieldInitializer.indexOf("\""); initializer = fieldInitializer.substring(offset + 1, fieldInitializer.lastIndexOf("\"")); } else { initializer = fieldName; } if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), VALIDATOR_CONSTRAINTS_EMAIL) != null || fieldName.toLowerCase().contains("email")) { initializer = "\"foo\" + " + INDEX_VAR + " + \"@bar.com\""; } else { int maxLength = Integer.MAX_VALUE; // Check for @Size final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null) { final AnnotationAttributeValue maxValue = sizeAnnotation.getAttribute(MAX_SYMBOL); if (maxValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "max", maxValue.getValue()); maxLength = ((Integer) maxValue.getValue()).intValue(); } final AnnotationAttributeValue minValue = sizeAnnotation.getAttribute(MIN_SYMBOL); if (minValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "min", minValue.getValue()); final int minLength = ((Integer) minValue.getValue()).intValue(); Validate.isTrue(maxLength >= minLength, "@Size attribute 'max' must be greater than 'min' for field '%s' in %s", fieldName, entity.getFullyQualifiedTypeName()); if (initializer.length() + 2 < minLength) { initializer = String.format("%1$-" + (minLength - 2) + "s", initializer).replace(' ', 'x'); } } } else { if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map columnValues = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (columnValues.keySet().contains("length")) { final Object lengthValue = columnValues.get("length"); validateNumericAnnotationAttribute(fieldName, "@Column", "length", lengthValue); maxLength = ((Integer) lengthValue).intValue(); } } } switch (maxLength) { case 0: initializer = "\"\""; break; case 1: initializer = "String.valueOf(" + INDEX_VAR + ")"; break; case 2: initializer = "\"" + initializer.charAt(0) + "\" + " + INDEX_VAR; break; default: if (initializer.length() + 2 > maxLength) { initializer = "\"" + initializer.substring(0, maxLength - 2) + "_\" + " + INDEX_VAR; } else { initializer = "\"" + initializer + "_\" + " + INDEX_VAR; } } } } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ \"Y\", \"N\" }"); } else if (fieldType.equals(JavaType.BOOLEAN_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "Boolean.TRUE"); } else if (fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "true"); } else if (fieldType.equals(JavaType.INT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ")"); } else if (fieldType.equals(JavaType.INT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, INDEX_VAR); } else if (fieldType.equals(new JavaType(JavaType.INT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ " + INDEX_VAR + ", " + INDEX_VAR + " }"); } else if (fieldType.equals(JavaType.DOUBLE_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); } else if (fieldType.equals(new JavaType(JavaType.DOUBLE_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").doubleValue(), new Integer(" + INDEX_VAR + ").doubleValue() }"); } else if (fieldType.equals(JavaType.FLOAT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); } else if (fieldType.equals(new JavaType(JavaType.FLOAT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").floatValue(), new Integer(" + INDEX_VAR + ").floatValue() }"); } else if (fieldType.equals(JavaType.LONG_OBJECT)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.LONG_PRIMITIVE)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); } else if (fieldType.equals(new JavaType(JavaType.LONG_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").longValue(), new Integer(" + INDEX_VAR + ").longValue() }"); } else if (fieldType.equals(JavaType.SHORT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.SHORT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); } else if (fieldType.equals(new JavaType(JavaType.SHORT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").shortValue(), new Integer(" + INDEX_VAR + ").shortValue() }"); } else if (fieldType.equals(JavaType.CHAR_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Character('N')"); } else if (fieldType.equals(JavaType.CHAR_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "'N'"); } else if (fieldType.equals(new JavaType(JavaType.CHAR_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ 'Y', 'N' }"); } else if (fieldType.equals(BIG_DECIMAL)) { builder.getImportRegistrationResolver().addImport(BIG_DECIMAL); initializer = BIG_DECIMAL.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(BIG_INTEGER)) { builder.getImportRegistrationResolver().addImport(BIG_INTEGER); initializer = BIG_INTEGER.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(JavaType.BYTE_OBJECT)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ")"; } else if (fieldType.equals(JavaType.BYTE_PRIMITIVE)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ").byteValue()"; } else if (fieldType.equals(JavaType.BYTE_ARRAY_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "String.valueOf(" + INDEX_VAR + ").getBytes()"); } else if (fieldType.equals(entity)) { // Avoid circular references (ROO-562) initializer = OBJ_VAR; } else if (fieldCustomDataKeys.contains(CustomDataKeys.ENUMERATED_FIELD)) { builder.getImportRegistrationResolver().addImport(fieldType); initializer = fieldType.getSimpleTypeName() + ".class.getEnumConstants()[0]"; } else if (collaboratingMetadata != null && collaboratingMetadata.getEntityType() != null) { requiredDataOnDemandCollaborators.add(fieldType); initializer = getFieldInitializerForRelatedEntity(field, collaboratingMetadata, fieldCustomDataKeys, dataOnDemandClasses); } return initializer; } private String getFieldInitializerForRelatedEntity(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set fieldCustomDataKeys, final Set dataOnDemandClasses) { // To avoid circular references, we don't try to set nullable fields final boolean nullableField = field.getAnnotation(NOT_NULL) == null && isNullableJoinColumn(field); if (nullableField) { return null; } JavaSymbolName collaboratingFieldName = getCollaboratingFieldName(field.getFieldType(), dataOnDemandClasses); if (collaboratingFieldName != null) { final String collaboratingName = collaboratingFieldName.getSymbolName(); if (fieldCustomDataKeys.contains(CustomDataKeys.ONE_TO_ONE_FIELD)) { // We try to keep the same ID (ROO-568) return collaboratingName + "." + SPECIFIC_METHOD_PREFIX.getSymbolName() + "(" + INDEX_VAR + ")"; } return collaboratingName + "." + collaboratingMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()"; } else { return null; } } private List getFieldMutatorMethods() { final List fieldMutatorMethods = new ArrayList(); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; for (final Map.Entry entry : fieldInitializers.entrySet()) { final FieldMetadata field = entry.getKey(); final JavaSymbolName mutatorName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); // Locate user-defined method if (governorHasMethod(mutatorName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } // Method not on governor so need to create it final String initializer = entry.getValue(); if (!StringUtils.isBlank(initializer)) { final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, mutatorName, false)); fieldMutatorMethods.add(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, mutatorName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } return fieldMutatorMethods; } private String getFieldValidationBody(final FieldMetadata field, final String initializer, final JavaSymbolName mutatorName, final boolean isFieldOfEmbeddableType) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); String suffix = ""; if (fieldType.equals(JavaType.LONG_OBJECT) || fieldType.equals(JavaType.LONG_PRIMITIVE)) { suffix = "L"; } else if (fieldType.equals(JavaType.FLOAT_OBJECT) || fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { suffix = "F"; } else if (fieldType.equals(JavaType.DOUBLE_OBJECT) || fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { suffix = "D"; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(getTypeStr(fieldType) + " " + fieldName + " = " + initializer + ";"); if (fieldType.equals(JavaType.STRING)) { boolean isUnique = isFieldOfEmbeddableType; @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (!isUnique && values != null && values.containsKey("unique")) { isUnique = (Boolean) values.get("unique"); } // Check for @Size or @Column with length attribute final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null && sizeAnnotation.getAttribute(MAX_SYMBOL) != null) { final Integer maxValue = (Integer) sizeAnnotation.getAttribute(MAX_SYMBOL).getValue(); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + maxValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + maxValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + maxValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (sizeAnnotation == null && values != null) { if (values.containsKey("length")) { final Integer lengthValue = (Integer) values.get("length"); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + lengthValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + lengthValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + lengthValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } else if (JdkJavaType.isDecimalType(fieldType)) { // Check for @Digits, @DecimalMax, @DecimalMin final AnnotationMetadata digitsAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DIGITS); final AnnotationMetadata decimalMinAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MIN); final AnnotationMetadata decimalMaxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MAX); if (digitsAnnotation != null) { bodyBuilder.append(getDigitsBody(field, digitsAnnotation, suffix)); } else if (decimalMinAnnotation != null || decimalMaxAnnotation != null) { bodyBuilder.append(getDecimalMinAndDecimalMaxBody(field, decimalMinAnnotation, decimalMaxAnnotation, suffix)); } else if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); bodyBuilder.append(getColumnPrecisionAndScaleBody(field, values, suffix)); } } else if (JdkJavaType.isIntegerType(fieldType)) { // Check for @Min and @Max bodyBuilder.append(getMinAndMaxBody(field, suffix)); } if (mutatorName != null) { bodyBuilder.appendFormalLine(OBJ_VAR + "." + mutatorName.getSymbolName() + "(" + fieldName + ");"); } return bodyBuilder.getOutput(); } private MethodMetadataBuilder getEmbeddedClassMutatorMethod(final EmbeddedHolder embeddedHolder) { final JavaSymbolName methodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName()); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded class final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedFieldType); bodyBuilder.appendFormalLine(embeddedFieldType.getSimpleTypeName() + " embeddedClass = new " + embeddedFieldType.getSimpleTypeName() + "();"); for (final FieldMetadata field : embeddedHolder.getFields()) { bodyBuilder.appendFormalLine(getEmbeddedFieldMutatorMethodName( embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()).getSymbolName() + "(embeddedClass, " + INDEX_VAR + ");"); } bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedHolder.getEmbeddedMutatorMethodName() + "(embeddedClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private MethodMetadataBuilder getEmbeddedIdMutatorMethod( final Set dataOnDemandClasses) { if (!hasEmbeddedIdentifier()) { return null; } final JavaSymbolName embeddedIdMutator = embeddedIdHolder.getEmbeddedIdMutator(); final JavaSymbolName methodName = getEmbeddedIdMutatorMethodName(); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded id class final JavaType embeddedIdFieldType = embeddedIdHolder.getEmbeddedIdField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedIdFieldType); final StringBuilder sb = new StringBuilder(); final List identifierFields = embeddedIdHolder.getIdFields(); for (int i = 0, n = identifierFields.size(); i < n; i++) { if (i > 0) { sb.append(", "); } final FieldMetadata field = identifierFields.get(i); final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); builder.getImportRegistrationResolver().addImport(fieldType); final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); bodyBuilder.append(getFieldValidationBody(field, initializer, null, true)); sb.append(fieldName); } bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine(embeddedIdFieldType.getSimpleTypeName() + " embeddedIdClass = new " + embeddedIdFieldType.getSimpleTypeName() + "(" + sb.toString() + ");"); bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedIdMutator + "(embeddedIdClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private String getMinAndMaxBody(final FieldMetadata field, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); final AnnotationMetadata minAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN); final AnnotationMetadata maxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX); if (minAnnotation != null && maxAnnotation == null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation == null && maxAnnotation != null) { final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation != null && maxAnnotation != null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue(maxValue.longValue() >= minValue.longValue(), "The value of @Max must be greater or equal to the value of @Min for field %s", fieldName); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getTypeStr(final JavaType fieldType) { builder.getImportRegistrationResolver().addImport(fieldType); final String arrayStr = fieldType.isArray() ? "[]" : ""; String typeStr = fieldType.getSimpleTypeName(); if (fieldType.getFullyQualifiedTypeName().equals( JavaType.FLOAT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "float" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.DOUBLE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "double" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.INT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "int" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.SHORT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "short" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.BYTE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "byte" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.CHAR_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "char" + arrayStr; } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { typeStr = "String[]"; } return typeStr; } private boolean isNullableJoinColumn(final FieldMetadata field) { final AnnotationMetadata joinColumnAnnotation = field.getAnnotation(JOIN_COLUMN); if (joinColumnAnnotation == null) { return true; } final AnnotationAttributeValue nullableAttr = joinColumnAnnotation.getAttribute(new JavaSymbolName("nullable")); return nullableAttr == null || (Boolean) nullableAttr.getValue(); } private void validateNumericAnnotationAttribute(final String fieldName, final String annotationName, final String attributeName, final Object object) { Validate.isTrue(NumberUtils.isNumber(object.toString()), "%s '%s' attribute for field '%s' in backing type %s must be numeric", annotationName, attributeName, fieldName, entity.getFullyQualifiedTypeName()); } public JavaSymbolName getCreateFactoryMethodName() { return JpaEntityFactoryMetadata.CREATE_FACTORY_METHOD_NAME; } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName fieldName) { return BeanInfoUtils.getMutatorMethodName(fieldName); } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName embeddedFieldName, final JavaSymbolName fieldName) { return getEmbeddedFieldMutatorMethodName(new JavaSymbolName(embeddedFieldName.getSymbolName() + StringUtils.capitalize(fieldName.getSymbolName()))); } public List getEmbeddedHolders() { return this.embeddedHolders; } public JavaSymbolName getEmbeddedIdMutatorMethodName() { final List fieldNames = new ArrayList(); for (final FieldMetadata field : fieldInitializers.keySet()) { fieldNames.add(field.getFieldName()); } int index = -1; JavaSymbolName embeddedIdField; while (true) { // Compute the required field name index++; embeddedIdField = new JavaSymbolName("embeddedIdClass" + StringUtils.repeat("_", index)); if (!fieldNames.contains(embeddedIdField)) { // Found a usable name break; } } return BeanInfoUtils.getMutatorMethodName(embeddedIdField); } public JavaType getEntityType() { return this.entity; } /** * Returns the {@link JavaType} representing the physical type of this ITD governor. * * @return the {@link JavaType} for the governor physical type. */ public JavaType getGovernorType() { return this.governorPhysicalTypeMetadata.getType(); } /** * @return the "getRandomEntity():Entity" method (never returns null) */ public MethodMetadata getRandomPersistentEntityMethod() { return randomPersistentEntityMethod; } public boolean hasEmbeddedIdentifier() { return this.embeddedIdHolder != null; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } } |
blob | long method | t | t | f | long method | blob | 0 | 12601 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadata.java/#L77-L1176 | 1 | 4699 | 12601 | critical |
| 2250 | { "message": "YES I found bad smells", "bad smells are": [ "Feature envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13669 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 1 | 2250 | 13669 | minor |
| 1622 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11487 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 1 | 1622 | 11487 | minor |
| 494 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 4985 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 494 | 4985 | minor |
| 2407 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 14389 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 2407 | 14389 | minor |
| 2452 | YES I found bad smells. the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Inappropriate Naming 5. Data Clumps 6. Shotgun Surgery 7. Divergent Change 8. Large Class 9. Primitive Obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | Long Method2 Feature Envy3 Duplicate Code4 Inappropriate Naming5 Data Clumps6 Shotgun Surgery7 Divergent Change8 Large Class9 Primitive Obsession | t | f | f | . Long Method2. Feature Envy3. Duplicate Code4. Inappropriate Naming5. Data Clumps6. Shotgun Surgery7. Divergent Change8. Large Class9. Primitive Obsession | data class | 0 | 14514 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 2 | 2452 | 14514 | minor |
| 172 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } } |
blob | long method | t | t | f | long method | blob | 0 | 2039 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 | 2 | 172 | 2039 | critical |
| 2621 | YES I found bad smells the bad smells are: 1. Long class 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Long class2 Long method | t | f | f | . Long class2. Long method | data class | 0 | 15056 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2621 | 15056 | minor |
| 1756 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
blob | long method | t | t | f | long method | blob | 0 | 11876 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 1756 | 11876 | minor |
| 1655 | {"response": "YES I found bad smells the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | t | f | f | data class | 0 | 11587 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 1 | 1655 | 11587 | minor | ||
| 1329 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10707 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 1329 | 10707 | critical |
| 5190 | NO, I did not find any bad smell in this code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14510 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5190 | 14510 | minor | ||
| 4113 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
data class | Long method2 Feature envy3 Large class4 Long parameter list | t | f | f | . Long method2. Feature envy3. Large class4. Long parameter list | data class | 0 | 10831 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 2 | 4113 | 10831 | minor |
| 116 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BeanRegistration { private final Class annotatedClass; @Nullable private final Supplier supplier; private final Class[] qualifiers; public BeanRegistration( Class annotatedClass, @Nullable Supplier supplier, Class[] qualifiers) { this.annotatedClass = annotatedClass; this.supplier = supplier; this.qualifiers = qualifiers; } public Class getAnnotatedClass() { return this.annotatedClass; } @Nullable @SuppressWarnings("rawtypes") public Supplier getSupplier() { return this.supplier; } public Class[] getQualifiers() { return this.qualifiers; } @Override public String toString() { return this.annotatedClass.getName(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1503 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java/#L342-L376 | 2 | 116 | 1503 | major |
| 1281 | YES I found bad smells YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class used as interface 4. Anemic domain model 5. Code duplication 6. Nested classes without clear hierarchy or purpose 7. Use of interface for a single implementation class 8. Overriding default method in interface 9. Misuse of the Builder pattern 10. Mismatched naming conventions 11. Poor encapsulation and information hiding | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } } |
blob | Long method2 Feature envy3 Data class used as interface4 Anemic domain model5 Code duplication6 Nested classes without clear hierarchy or purpose7 Use of interface for a single implementation class8 Overriding default method in interface9 Misuse of the Builder pattern | t | f | f | . Long method2. Feature envy3. Data class used as interface4. Anemic domain model5. Code duplication6. Nested classes without clear hierarchy or purpose7. Use of interface for a single implementation class8. Overriding default method in interface9. Misuse of the Builder pattern | blob | 0 | 10595 | https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 | 2 | 1281 | 10595 | minor |
| 3943 | . YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (addActionListener method should be moved to another class that has a more suitable relation to it) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | Long method 2 Feature envy (addActionListener method should be moved to another class that has a more suitable relation to it) | t | f | f | . Long method 2. Feature envy (addActionListener method should be moved to another class that has a more suitable relation to it) | blob | 0 | 10322 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 2 | 3943 | 10322 | minor |
| 470 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({ "unchecked", "rawtypes" }) public final class CorePlugin extends Plugin { public static final String PLUGIN_ID = "org.eclipse.buildship.core"; //$NON-NLS-1$ public static final String GRADLE_JOB_FAMILY = PLUGIN_ID + ".jobs"; private static CorePlugin plugin; // do not use generics-aware signature since this causes compilation troubles (JDK, Spock) // search the web for -target jsr14 to find out more about this obscurity private ServiceRegistration loggerService; private ServiceRegistration publishedGradleVersionsService; private ServiceRegistration workspaceOperationsService; private ServiceRegistration internalGradleWorkspaceService; private ServiceRegistration processStreamsProviderService; private ServiceRegistration gradleLaunchConfigurationService; private ServiceRegistration listenerRegistryService; // service tracker for each service to allow to register other service implementations of the // same type but with higher prioritization, useful for testing private ServiceTracker loggerServiceTracker; private ServiceTracker publishedGradleVersionsServiceTracker; private ServiceTracker workspaceOperationsServiceTracker; private ServiceTracker internalGradleWorkspaceServiceTracker; private ServiceTracker processStreamsProviderServiceTracker; private ServiceTracker gradleLaunchConfigurationServiceTracker; private ServiceTracker listenerRegistryServiceTracker; private DefaultModelPersistence modelPersistence; private ProjectChangeListener projectChangeListener; private SynchronizingBuildScriptUpdateListener buildScriptUpdateListener; private InvocationCustomizer invocationCustomizer; private ConfigurationManager configurationManager; private DefaultExternalLaunchConfigurationManager externalLaunchConfigurationManager; private ToolingApiOperationManager operationManager; private ExtensionManager extensionManager; @Override public void start(BundleContext bundleContext) throws Exception { super.start(bundleContext); plugin = this; ensureProxySettingsApplied(); registerServices(bundleContext); } @Override public void stop(BundleContext context) throws Exception { unregisterServices(); plugin = null; super.stop(context); } private void ensureProxySettingsApplied() throws Exception { // the proxy settings are set when the core.net plugin is started Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT); } private void registerServices(BundleContext context) { // store services with low ranking such that they can be overridden // during testing or the like Dictionary preferences = new Hashtable<>(); preferences.put(Constants.SERVICE_RANKING, 1); // initialize service trackers before the services are created this.loggerServiceTracker = createServiceTracker(context, Logger.class); this.publishedGradleVersionsServiceTracker = createServiceTracker(context, PublishedGradleVersionsWrapper.class); this.workspaceOperationsServiceTracker = createServiceTracker(context, WorkspaceOperations.class); this.internalGradleWorkspaceServiceTracker = createServiceTracker(context, InternalGradleWorkspace.class); this.processStreamsProviderServiceTracker = createServiceTracker(context, ProcessStreamsProvider.class); this.gradleLaunchConfigurationServiceTracker = createServiceTracker(context, GradleLaunchConfigurationManager.class); this.listenerRegistryServiceTracker = createServiceTracker(context, ListenerRegistry.class); // register all services this.loggerService = registerService(context, Logger.class, createLogger(), preferences); this.publishedGradleVersionsService = registerService(context, PublishedGradleVersionsWrapper.class, createPublishedGradleVersions(), preferences); this.workspaceOperationsService = registerService(context, WorkspaceOperations.class, createWorkspaceOperations(), preferences); this.internalGradleWorkspaceService = registerService(context, InternalGradleWorkspace.class, createGradleWorkspace(), preferences); this.processStreamsProviderService = registerService(context, ProcessStreamsProvider.class, createProcessStreamsProvider(), preferences); this.gradleLaunchConfigurationService = registerService(context, GradleLaunchConfigurationManager.class, createGradleLaunchConfigurationManager(), preferences); this.listenerRegistryService = registerService(context, ListenerRegistry.class, createListenerRegistry(), preferences); this.modelPersistence = DefaultModelPersistence.createAndRegister(); this.projectChangeListener = ProjectChangeListener.createAndRegister(); this.buildScriptUpdateListener = SynchronizingBuildScriptUpdateListener.createAndRegister(); this.invocationCustomizer = new InvocationCustomizerCollector(); this.configurationManager = new DefaultConfigurationManager(); this.externalLaunchConfigurationManager = DefaultExternalLaunchConfigurationManager.createAndRegister(); this.operationManager = new DefaultToolingApiOperationManager(); this.extensionManager = new DefaultExtensionManager(); } private ServiceTracker createServiceTracker(BundleContext context, Class clazz) { ServiceTracker serviceTracker = new ServiceTracker(context, clazz.getName(), null); serviceTracker.open(); return serviceTracker; } private ServiceRegistration registerService(BundleContext context, Class clazz, T service, Dictionary properties) { return context.registerService(clazz.getName(), service, properties); } private EclipseLogger createLogger() { Map tracingEnablement = Maps.newHashMap(); for (TraceScope scope : CoreTraceScopes.values()) { String option = Platform.getDebugOption("org.eclipse.buildship.core/trace/" + scope.getScopeKey()); tracingEnablement.put(scope, "true".equalsIgnoreCase(option)); } return new EclipseLogger(getLog(), PLUGIN_ID, tracingEnablement); } private PublishedGradleVersionsWrapper createPublishedGradleVersions() { return new PublishedGradleVersionsWrapper(); } private WorkspaceOperations createWorkspaceOperations() { return new DefaultWorkspaceOperations(); } private InternalGradleWorkspace createGradleWorkspace() { return new DefaultGradleWorkspace(); } private ProcessStreamsProvider createProcessStreamsProvider() { return new StdProcessStreamsProvider(); } private GradleLaunchConfigurationManager createGradleLaunchConfigurationManager() { return new DefaultGradleLaunchConfigurationManager(); } private ListenerRegistry createListenerRegistry() { return new DefaultListenerRegistry(); } private void unregisterServices() { this.externalLaunchConfigurationManager.unregister(); this.buildScriptUpdateListener.close(); this.projectChangeListener.close(); this.modelPersistence.close(); this.listenerRegistryService.unregister(); this.gradleLaunchConfigurationService.unregister(); this.processStreamsProviderService.unregister(); this.internalGradleWorkspaceService.unregister(); this.workspaceOperationsService.unregister(); this.publishedGradleVersionsService.unregister(); this.loggerService.unregister(); this.listenerRegistryServiceTracker.close(); this.gradleLaunchConfigurationServiceTracker.close(); this.processStreamsProviderServiceTracker.close(); this.internalGradleWorkspaceServiceTracker.close(); this.workspaceOperationsServiceTracker.close(); this.publishedGradleVersionsServiceTracker.close(); this.loggerServiceTracker.close(); } public static CorePlugin getInstance() { return plugin; } public static Logger logger() { return (Logger) getInstance().loggerServiceTracker.getService(); } public static PublishedGradleVersionsWrapper publishedGradleVersions() { return (PublishedGradleVersionsWrapper) getInstance().publishedGradleVersionsServiceTracker.getService(); } public static WorkspaceOperations workspaceOperations() { return (WorkspaceOperations) getInstance().workspaceOperationsServiceTracker.getService(); } public static InternalGradleWorkspace internalGradleWorkspace() { return (InternalGradleWorkspace) getInstance().internalGradleWorkspaceServiceTracker.getService(); } public static ProcessStreamsProvider processStreamsProvider() { return (ProcessStreamsProvider) getInstance().processStreamsProviderServiceTracker.getService(); } public static GradleLaunchConfigurationManager gradleLaunchConfigurationManager() { return (GradleLaunchConfigurationManager) getInstance().gradleLaunchConfigurationServiceTracker.getService(); } public static ListenerRegistry listenerRegistry() { return (ListenerRegistry) getInstance().listenerRegistryServiceTracker.getService(); } public static ModelPersistence modelPersistence() { return getInstance().modelPersistence; } public static InvocationCustomizer invocationCustomizer() { return getInstance().invocationCustomizer; } public static ConfigurationManager configurationManager() { return getInstance().configurationManager; } public static ExternalLaunchConfigurationManager externalLaunchConfigurationManager() { return getInstance().externalLaunchConfigurationManager; } public static ToolingApiOperationManager operationManager() { return getInstance().operationManager; } public static ExtensionManager extensionManager() { return getInstance().extensionManager; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 4563 | https://github.com/eclipse/buildship/blob/3111a7a9fe3e22d6123366686874ecd42aa2a53a/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/CorePlugin.java/#L70-L282 | 1 | 470 | 4563 | major |
| 2301 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14036 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 2 | 2301 | 14036 | minor |
| 5057 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14131 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 5057 | 14131 | minor |
| 1575 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11348 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 1575 | 11348 | minor |
| 2616 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15048 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 2616 | 15048 | major |
| 1376 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 10810 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 1376 | 10810 | major |
| 2207 | {"YES I found bad smells":true,"the bad smells are:":["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 13515 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 2207 | 13515 | minor |
| 4074 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10748 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 4074 | 10748 | minor |
| 926 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | data class | t | t | f | data class | blob | 0 | 8312 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 926 | 8312 | critical |
| 2384 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
blob | data class | t | t | f | data class | blob | 0 | 14343 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 1 | 2384 | 14343 | minor |
| 1960 | { "output": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 12583 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 1 | 1960 | 12583 | minor |
| 1344 | { "error": "Please check the list of common code smells in the input and specify what bad smells are listed." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Not specified | f | f | f | false | 0 | 10746 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1344 | 10746 | major | |
| 2534 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14749 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 2 | 2534 | 14749 | major |
| 235 | {"message": "YES I found bad smells", "bad smells": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class SequenceTermination extends TimerTask { private long maxInactivityTimeout; void updateInactivityTimeout(long timeout) { maxInactivityTimeout = Math.max(maxInactivityTimeout, timeout); } public void run() { synchronized (DestinationSequence.this) { DestinationSequence.this.scheduledTermination = null; RMEndpoint rme = destination.getReliableEndpoint(); long lat = Math.max(rme.getLastControlMessage(), rme.getLastApplicationMessage()); if (0 == lat) { return; } long now = System.currentTimeMillis(); if (now - lat >= maxInactivityTimeout) { // terminate regardless outstanding acknowledgments - as we assume that the client is // gone there is no point in sending a SequenceAcknowledgment LogUtils.log(LOG, Level.WARNING, "TERMINATING_INACTIVE_SEQ_MSG", DestinationSequence.this.getIdentifier().getValue()); DestinationSequence.this.destination.terminateSequence(DestinationSequence.this, true); Source source = rme.getSource(); if (source != null) { SourceSequence ss = source.getAssociatedSequence(DestinationSequence.this.getIdentifier()); if (ss != null) { source.removeSequence(ss); } } } else { // reschedule SequenceTermination st = new SequenceTermination(); st.updateInactivityTimeout(maxInactivityTimeout); DestinationSequence.this.destination.getManager().getTimer() .schedule(st, maxInactivityTimeout); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2555 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/rm/src/main/java/org/apache/cxf/ws/rm/DestinationSequence.java/#L565-L605 | 1 | 235 | 2555 | minor |
| 2449 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14500 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 2 | 2449 | 14500 | minor |
| 1391 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BucketList implements Iterable> { private final ArrayList> bucketList; private final List> immutableVisibleList; private BucketList(ArrayList> bucketList, ArrayList> publicBucketList) { this.bucketList = bucketList; int displayIndex = 0; for (Bucket bucket : publicBucketList) { bucket.displayIndex = displayIndex++; } immutableVisibleList = Collections.unmodifiableList(publicBucketList); } private int getBucketCount() { return immutableVisibleList.size(); } private int getBucketIndex(CharSequence name, Collator collatorPrimaryOnly) { // binary search int start = 0; int limit = bucketList.size(); while ((start + 1) < limit) { int i = (start + limit) / 2; Bucket bucket = bucketList.get(i); int nameVsBucket = collatorPrimaryOnly.compare(name, bucket.lowerBoundary); if (nameVsBucket < 0) { limit = i; } else { start = i; } } Bucket bucket = bucketList.get(start); if (bucket.displayBucket != null) { bucket = bucket.displayBucket; } return bucket.displayIndex; } /** * Private iterator over all the buckets, visible and invisible */ private Iterator> fullIterator() { return bucketList.iterator(); } /** * Iterator over just the visible buckets. */ @Override public Iterator> iterator() { return immutableVisibleList.iterator(); // use immutable list to prevent remove(). } } |
blob | Not specified | f | f | f | false | 0 | 10842 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/AlphabeticIndex.java/#L1101-L1154 | 1 | 1391 | 10842 | minor | |
| 1546 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent indentation 5. Commented out code 6. Unused imports 7. Unused variables 8. Unused method arguments 9. Lack of proper exception handling 10. Multiple responsibilities in one class (violation of Single Responsibility Principle) 11. Use of magic numbers and strings instead of constants or enums 12. Inconsistent naming conventions for variables and methods 13. Use of raw types instead of generics 14. Mixing business logic with framework or infrastructure code 15. Tight coupling and lack of dependency injection 16. Lack of proper documentation or unclear comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Service ("knownRepositoryContentConsumer#create-archiva-metadata") @Scope ("prototype") public class ArchivaMetadataCreationConsumer extends AbstractMonitoredConsumer implements KnownRepositoryContentConsumer, RegistryListener { private String id = "create-archiva-metadata"; private String description = "Create basic metadata for Archiva to be able to reference the artifact"; @Inject private ArchivaConfiguration configuration; @Inject private FileTypes filetypes; private Date whenGathered; private List includes = new ArrayList<>( 0 ); /** * FIXME: this could be multiple implementations and needs to be configured. */ @Inject private RepositorySessionFactory repositorySessionFactory; /** * FIXME: this needs to be configurable based on storage type - and could also be instantiated per repo. Change to a * factory. */ @Inject @Named (value = "repositoryStorage#maven2") private RepositoryStorage repositoryStorage; private static final Logger log = LoggerFactory.getLogger( ArchivaMetadataCreationConsumer.class ); private String repoId; @Override public String getId() { return this.id; } @Override public String getDescription() { return this.description; } @Override public List getExcludes() { return getDefaultArtifactExclusions(); } @Override public List getIncludes() { return this.includes; } @Override public void beginScan( ManagedRepository repo, Date whenGathered ) throws ConsumerException { repoId = repo.getId(); this.whenGathered = whenGathered; } @Override public void beginScan( ManagedRepository repository, Date whenGathered, boolean executeOnEntireRepo ) throws ConsumerException { beginScan( repository, whenGathered ); } @Override public void processFile( String path ) throws ConsumerException { RepositorySession repositorySession = repositorySessionFactory.createSession(); try { // note that we do minimal processing including checksums and POM information for performance of // the initial scan. Any request for this information will be intercepted and populated on-demand // or picked up by subsequent scans ArtifactMetadata artifact = repositoryStorage.readArtifactMetadataFromPath( repoId, path ); ProjectMetadata project = new ProjectMetadata(); project.setNamespace( artifact.getNamespace() ); project.setId( artifact.getProject() ); String projectVersion = VersionUtil.getBaseVersion( artifact.getVersion() ); MetadataRepository metadataRepository = repositorySession.getRepository(); boolean createVersionMetadata = false; // FIXME: maybe not too efficient since it may have already been read and stored for this artifact ProjectVersionMetadata versionMetadata = null; try { ReadMetadataRequest readMetadataRequest = new ReadMetadataRequest().repositoryId( repoId ).namespace( artifact.getNamespace() ).projectId( artifact.getProject() ).projectVersion( projectVersion ); versionMetadata = repositoryStorage.readProjectVersionMetadata( readMetadataRequest ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataNotFoundException e ) { log.warn( "Missing or invalid POM for artifact:{} (repository:{}); creating empty metadata", path, repoId ); versionMetadata = new ProjectVersionMetadata(); versionMetadata.setId( projectVersion ); versionMetadata.setIncomplete( true ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataInvalidException e ) { log.warn( "Error occurred resolving POM for artifact:{} (repository:{}); message: {}", new Object[]{ path, repoId, e.getMessage() } ); } // read the metadata and update it if it is newer or doesn't exist artifact.setWhenGathered( whenGathered ); metadataRepository.updateArtifact( repoId, project.getNamespace(), project.getId(), projectVersion, artifact ); if ( createVersionMetadata ) { metadataRepository.updateProjectVersion( repoId, project.getNamespace(), project.getId(), versionMetadata ); } metadataRepository.updateProject( repoId, project ); repositorySession.save(); } catch ( MetadataRepositoryException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}" , path, repoId, e.getMessage(), e ); repositorySession.revert(); } catch ( RepositoryStorageRuntimeException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}", path, repoId, e.getMessage(), e ); repositorySession.revert(); } finally { repositorySession.close(); } } @Override public void processFile( String path, boolean executeOnEntireRepo ) throws ConsumerException { processFile( path ); } @Override public void completeScan() { /* do nothing */ } @Override public void completeScan( boolean executeOnEntireRepo ) { completeScan(); } @Override public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { if ( ConfigurationNames.isRepositoryScanning( propertyName ) ) { initIncludes(); } } @Override public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { /* do nothing */ } private void initIncludes() { includes = new ArrayList( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) ); } @PostConstruct public void initialize() { configuration.addChangeListener( this ); initIncludes(); } } |
blob | Long method2 Feature envy3 Duplicate code4 Inconsistent indentation5 Commented out code6 Unused imports7 Unused variables8 Unused method arguments9 Lack of proper exception handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent indentation5. Commented out code6. Unused imports7. Unused variables8. Unused method arguments9. Lack of proper exception handling | blob | 0 | 11252 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-consumers/archiva-metadata-consumer/src/main/java/org/apache/archiva/consumers/metadata/ArchivaMetadataCreationConsumer.java/#L59-L264 | 2 | 1546 | 11252 | minor |
| 4451 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 11797 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 1 | 4451 | 11797 | minor |
| 852 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CConstantValueSupportImpl implements CConstantValueSupport { private final NativeLibraries nativeLibraries; private final MetaAccessProvider metaAccess; public CConstantValueSupportImpl(NativeLibraries nativeLibraries, MetaAccessProvider metaAccess) { this.nativeLibraries = nativeLibraries; this.metaAccess = metaAccess; } @Override public T getCConstantValue(Class declaringClass, String methodName, Class returnType) { ResolvedJavaMethod method; try { method = metaAccess.lookupJavaMethod(declaringClass.getMethod(methodName)); } catch (NoSuchMethodException | SecurityException e) { throw VMError.shouldNotReachHere("Method not found: " + declaringClass.getName() + "." + methodName); } if (method.getAnnotation(CConstant.class) == null) { throw VMError.shouldNotReachHere("Method " + declaringClass.getName() + "." + methodName + " is not annotated with @" + CConstant.class.getSimpleName()); } ConstantInfo constantInfo = (ConstantInfo) nativeLibraries.findElementInfo(method); Object value = constantInfo.getValueInfo().getProperty(); switch (constantInfo.getKind()) { case INTEGER: case POINTER: Long longValue = (Long) value; if (returnType == Boolean.class) { return returnType.cast(Boolean.valueOf(longValue.longValue() != 0)); } else if (returnType == Integer.class) { return returnType.cast(Integer.valueOf((int) longValue.longValue())); } else if (returnType == Long.class) { return returnType.cast(value); } break; case FLOAT: if (returnType == Double.class) { return returnType.cast(value); } break; case STRING: if (returnType == String.class) { return returnType.cast(value); } break; case BYTEARRAY: if (returnType == byte[].class) { return returnType.cast(value); } break; } throw VMError.shouldNotReachHere("Unexpected returnType: " + returnType.getName()); } } |
blob | long method | t | t | f | long method | blob | 0 | 7853 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/c/CConstantValueSupportImpl.java/#L36-L93 | 1 | 852 | 7853 | minor |
| 426 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object that) { if( !(that instanceof PlanningCoCodingGroup) ) return false; PlanningCoCodingGroup thatgrp = (PlanningCoCodingGroup) that; return Arrays.equals(_colIndexes, thatgrp._colIndexes); } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 4264 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/compress/cocode/PlanningCoCodingGroup.java/#L116-L123 | 1 | 426 | 4264 | minor |
| 623 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6248 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 623 | 6248 | minor |
| 1436 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | f | f | f | long method | 0 | 10962 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 1436 | 10962 | minor | ||
| 277 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 2971 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 | 1 | 277 | 2971 | minor |
| 3238 | YES, I found bad smells: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 5441 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 2 | 3238 | 5441 | minor |
| 596 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5950 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 2 | 596 | 5950 | minor |
| 63 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1067 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 63 | 1067 | major |
| 234 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2553 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 2 | 234 | 2553 | minor |
| 2094 | {"response": "YES, I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13142 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 2094 | 13142 | minor |
| 23 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 688 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 1 | 23 | 688 | minor |
| 844 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable public final class ConnectionValidator { private final Map specMap; private final QueryFilterCriteriaFactory queryFilterCriteriaFactory; private ConnectionValidator(final AbstractProtocolValidator... connectionSpecs) { final Map specMap = Arrays.stream(connectionSpecs) .collect(Collectors.toMap(AbstractProtocolValidator::type, Function.identity())); this.specMap = Collections.unmodifiableMap(specMap); final CriteriaFactory criteriaFactory = new CriteriaFactoryImpl(); final ThingsFieldExpressionFactory fieldExpressionFactory = new ModelBasedThingsFieldExpressionFactory(); queryFilterCriteriaFactory = new QueryFilterCriteriaFactory(criteriaFactory, fieldExpressionFactory); } /** * Create a connection validator from connection specs. * * @param connectionSpecs specs of supported connection types. * @return a connection validator. */ public static ConnectionValidator of(final AbstractProtocolValidator... connectionSpecs) { return new ConnectionValidator(connectionSpecs); } /** * Check a connection for errors and throw them. * * @param connection the connection to validate. * @param dittoHeaders headers of the command that triggered the connection validation. * @throws org.eclipse.ditto.model.base.exceptions.DittoRuntimeException if the connection has errors. * @throws java.lang.IllegalStateException if the connection type is not known. */ void validate(final Connection connection, final DittoHeaders dittoHeaders) { final AbstractProtocolValidator spec = specMap.get(connection.getConnectionType()); validateSourceAndTargetAddressesAreNonempty(connection, dittoHeaders); validateFormatOfCertificates(connection, dittoHeaders); if (spec != null) { // throw error at validation site for clarity of stack trace spec.validate(connection, dittoHeaders); } else { throw new IllegalStateException("Unknown connection type: " + connection); } } private void validateSourceAndTargetAddressesAreNonempty(final Connection connection, final DittoHeaders dittoHeaders) { connection.getSources().forEach(source -> { if (source.getAddresses().isEmpty() || source.getAddresses().contains("")) { final String location = String.format("Source %d of connection <%s>", source.getIndex(), connection.getId()); throw emptyAddressesError(location, dittoHeaders); } }); connection.getTargets().forEach(target -> { if (target.getAddress().isEmpty()) { final String location = String.format("Targets of connection <%s>", connection.getId()); throw emptyAddressesError(location, dittoHeaders); } target.getTopics().forEach(topic -> topic.getFilter().ifPresent(filter -> { // will throw an InvalidRqlExpressionException if the RQL expression was not valid: queryFilterCriteriaFactory.filterCriteria(filter, dittoHeaders); })); }); } private static void validateFormatOfCertificates(final Connection connection, final DittoHeaders dittoHeaders) { final Optional trustedCertificates = connection.getTrustedCertificates(); final Optional credentials = connection.getCredentials(); // check if there are certificates to check if (trustedCertificates.isPresent() || credentials.isPresent()) { credentials.orElseGet(ClientCertificateCredentials::empty) .accept(SSLContextCreator.fromConnection(connection, dittoHeaders)); } } private static DittoRuntimeException emptyAddressesError(final String location, final DittoHeaders dittoHeaders) { final String message = location + ": addresses may not be empty."; return ConnectionConfigurationInvalidException.newBuilder(message) .dittoHeaders(dittoHeaders) .build(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7807 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/connectivity/messaging/src/main/java/org/eclipse/ditto/services/connectivity/messaging/validation/ConnectionValidator.java/#L39-L125 | 1 | 844 | 7807 | minor |
| 112 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1463 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 1 | 112 | 1463 | major |
| 307 | YES, I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int getDVDTotalTitles() { if (bdp != null) return bdp.getNumTitles(); return 0; } |
feature envy | Long Method | t | f | f | . Long Method | feature envy | 0 | 3199 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/MiniPlayer.java/#L2879-L2884 | 2 | 307 | 3199 | critical |
| 1131 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class SwiftUtils { public static final String READ = "read(buffer, offset, length)"; /** * Join two (non null) paths, inserting a forward slash between them * if needed * * @param path1 first path * @param path2 second path * @return the combined path */ public static String joinPaths(String path1, String path2) { StringBuilder result = new StringBuilder(path1.length() + path2.length() + 1); result.append(path1); boolean insertSlash = true; if (path1.endsWith("/")) { insertSlash = false; } else if (path2.startsWith("/")) { insertSlash = false; } if (insertSlash) { result.append("/"); } result.append(path2); return result.toString(); } /** * This test contains the is-directory logic for Swift, so if * changed there is only one place for it. * * @param fileStatus status to examine * @return true if we consider this status to be representative of a * directory. */ public static boolean isDirectory(FileStatus fileStatus) { return fileStatus.isDirectory() || isFilePretendingToBeDirectory(fileStatus); } /** * Test for the entry being a file that is treated as if it is a * directory * * @param fileStatus status * @return true if it meets the rules for being a directory */ public static boolean isFilePretendingToBeDirectory(FileStatus fileStatus) { return fileStatus.getLen() == 0; } /** * Predicate: Is a swift object referring to the root directory? * @param swiftObject object to probe * @return true iff the object refers to the root */ public static boolean isRootDir(SwiftObjectPath swiftObject) { return swiftObject.objectMatches("") || swiftObject.objectMatches("/"); } /** * Sprintf() to the log iff the log is at debug level. If the log * is not at debug level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void debug(Logger log, String text, Object... args) { if (log.isDebugEnabled()) { log.debug(String.format(text, args)); } } /** * Log an exception (in text and trace) iff the log is at debug * @param log Log to use * @param text text message * @param ex exception */ public static void debugEx(Logger log, String text, Exception ex) { if (log.isDebugEnabled()) { log.debug(text + ex, ex); } } /** * Sprintf() to the log iff the log is at trace level. If the log * is not at trace level, the printf operation is skipped, so * no time is spent generating the string. * @param log log to use * @param text text message * @param args args arguments to the print statement */ public static void trace(Logger log, String text, Object... args) { if (log.isTraceEnabled()) { log.trace(String.format(text, args)); } } /** * Given a partition number, calculate the partition value. * This is used in the SwiftNativeOutputStream, and is placed * here for tests to be able to calculate the filename of * a partition. * @param partNumber part number * @return a string to use as the filename */ public static String partitionFilenameFromNumber(int partNumber) { return String.format("%06d", partNumber); } /** * List a a path to string * @param fileSystem filesystem * @param path directory * @return a listing of the filestatuses of elements in the directory, one * to a line, preceded by the full path of the directory * @throws IOException connectivity problems */ public static String ls(FileSystem fileSystem, Path path) throws IOException { if (path == null) { //surfaces when someone calls getParent() on something at the top of the path return "/"; } FileStatus[] stats; String pathtext = "ls " + path; try { stats = fileSystem.listStatus(path); } catch (FileNotFoundException e) { return pathtext + " -file not found"; } catch (IOException e) { return pathtext + " -failed: " + e; } return pathtext + fileStatsToString(stats, "\n"); } /** * Take an array of filestatus and convert to a string (prefixed w/ a [01] counter * @param stats array of stats * @param separator separator after every entry * @return a stringified set */ public static String fileStatsToString(FileStatus[] stats, String separator) { StringBuilder buf = new StringBuilder(stats.length * 128); for (int i = 0; i < stats.length; i++) { buf.append(String.format("[%02d] %s", i, stats[i])).append(separator); } return buf.toString(); } /** * Verify that the basic args to a read operation are valid; * throws an exception if not -with meaningful text including * @param buffer destination buffer * @param off offset * @param len number of bytes to read * @throws NullPointerException null buffer * @throws IndexOutOfBoundsException on any invalid range. */ public static void validateReadArgs(byte[] buffer, int off, int len) { if (buffer == null) { throw new NullPointerException("Null byte array in"+ READ); } if (off < 0 ) { throw new IndexOutOfBoundsException("Negative buffer offset " + off + " in " + READ); } if (len < 0 ) { throw new IndexOutOfBoundsException("Negative read length " + len + " in " + READ); } if (off > buffer.length) { throw new IndexOutOfBoundsException("Buffer offset of " + off + "beyond buffer size of " + buffer.length + " in " + READ); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10034 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-openstack/src/main/java/org/apache/hadoop/fs/swift/util/SwiftUtils.java/#L32-L216 | 2 | 1131 | 10034 | minor |
| 167 | { "output": "YES I found bad smells", "bad smells are": "1. Blob", "code smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | blob | t | t | f | blob | data class | 0 | 2023 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 1 | 167 | 2023 | major |
| 183 | { "response": "YES I found bad smells", "the bad smells are:": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2095 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 2 | 183 | 2095 | minor |
| 1872 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Data clumps 4. Inappropriate intimate method call | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
blob | Long method2 Magic numbers3 Data clumps4 Inappropriate intimate method call | t | f | f | . Long method2. Magic numbers3. Data clumps4. Inappropriate intimate method call | blob | 0 | 12250 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 1872 | 12250 | minor |
| 2604 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 15026 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 1 | 2604 | 15026 | major |
| 902 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @NodeInfo(cycles = CYCLES_2, size = SIZE_1) public final class BitScanForwardNode extends UnaryNode implements ArithmeticLIRLowerable { public static final NodeClass TYPE = NodeClass.create(BitScanForwardNode.class); public BitScanForwardNode(ValueNode value) { super(TYPE, StampFactory.forInteger(JavaKind.Int, 0, ((PrimitiveStamp) value.stamp(NodeView.DEFAULT)).getBits()), value); assert value.getStackKind() == JavaKind.Int || value.getStackKind() == JavaKind.Long; } @Override public Stamp foldStamp(Stamp newStamp) { assert newStamp.isCompatible(getValue().stamp(NodeView.DEFAULT)); IntegerStamp valueStamp = (IntegerStamp) newStamp; int min; int max; long mask = CodeUtil.mask(valueStamp.getBits()); int firstAlwaysSetBit = scan(valueStamp.downMask() & mask); int firstMaybeSetBit = scan(valueStamp.upMask() & mask); if (firstAlwaysSetBit == -1) { int lastMaybeSetBit = BitScanReverseNode.scan(valueStamp.upMask() & mask); min = firstMaybeSetBit; max = lastMaybeSetBit; } else { min = firstMaybeSetBit; max = firstAlwaysSetBit; } return StampFactory.forInteger(JavaKind.Int, min, max); } public static ValueNode tryFold(ValueNode value) { if (value.isConstant()) { JavaConstant c = value.asJavaConstant(); if (c.asLong() != 0) { return ConstantNode.forInt(value.getStackKind() == JavaKind.Int ? scan(c.asInt()) : scan(c.asLong())); } } return null; } @Override public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) { ValueNode folded = tryFold(forValue); return folded != null ? folded : this; } /** * Utility method with defined return value for 0. * * @param v * @return number of trailing zeros or -1 if {@code v} == 0. */ public static int scan(long v) { if (v == 0) { return -1; } return Long.numberOfTrailingZeros(v); } /** * Utility method with defined return value for 0. * * @param v * @return number of trailing zeros or -1 if {@code v} == 0. */ public static int scan(int v) { return scan(0xffffffffL & v); } /** * Raw intrinsic for bsf instruction. * * @param v * @return number of trailing zeros or an undefined value if {@code v} == 0. */ @NodeIntrinsic public static native int unsafeScan(long v); /** * Raw intrinsic for bsf instruction. * * @param v * @return number of trailing zeros or an undefined value if {@code v} == 0. */ @NodeIntrinsic public static native int unsafeScan(int v); @Override public void generate(NodeLIRBuilderTool builder, ArithmeticLIRGeneratorTool gen) { builder.setResult(this, gen.emitBitScanForward(builder.operand(getValue()))); } } |
blob | long method | t | t | f | long method | blob | 0 | 8167 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/BitScanForwardNode.java/#L53-L144 | 1 | 902 | 8167 | minor |
| 1232 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10367 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1232 | 10367 | major |
| 969 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8680 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 2 | 969 | 8680 | major |
| 818 | {"message": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | "YES I found bad smells", "bad smells" | t | f | f | "YES I found bad smells", "bad smells" | blob | 0 | 7672 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 818 | 7672 | critical |
| 980 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | long method | t | t | f | long method | data class | 0 | 8852 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 980 | 8852 | major |
| 1707 | {"message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
blob | data class | t | t | f | data class | blob | 0 | 11755 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 1707 | 11755 | critical |
| 1705 | { "message": "YES, I found bad smells", "the bad smells are": { "1. Long method": "AnnotationViewerMain constructor", "2. Feature envy": "Several ActionListener classes inside the AnnotationViewerMain class" } } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } } |
blob | 1. long method: annotationviewermain constructor, 2. feature envy: several actionlistener classes inside the annotationviewermain class | t | t | f | 1. long method: annotationviewermain constructor, 2. feature envy: several actionlistener classes inside the annotationviewermain class | blob | 0 | 11749 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 | 2 | 1705 | 11749 | major |
| 1109 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9883 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 2 | 1109 | 9883 | minor |
| 2168 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Not specified | f | f | f | false | 0 | 13354 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 2168 | 13354 | minor | |
| 1868 | { "NO, I did not find any bad smell" | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
blob | f | f | f | blob | 0 | 12244 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 1868 | 12244 | critical | ||
| 233 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NsTestPrintStream extends PrintStream { /////////////////////////////////////////////////////////////////////////////////// // // CONSTANTS // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // STATE // /////////////////////////////////////////////////////////////////////////////////// private boolean _chatty; /////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR // /////////////////////////////////////////////////////////////////////////////////// /** Construct a quiet or chatty print stream */ public NsTestPrintStream( PrintStream wrappedStream, boolean chatty ) { super( wrappedStream ); _chatty = chatty; } /////////////////////////////////////////////////////////////////////////////////// // // OVERRIDDEN BEHAVIOR // /////////////////////////////////////////////////////////////////////////////////// public PrintStream append( char c ) { if ( _chatty ) { super.append( c ); } return this; } public PrintStream append( CharSequence csq ) { if ( _chatty ) { super.append( csq ); } return this; } public PrintStream append( CharSequence csq, int start, int end ) { if ( _chatty ) { super.append( csq, start, end ); } return this; } public boolean checkError() { return super.checkError(); } protected void clearError() { super.clearError(); } public void close() { super.close(); } public void flush() { super.flush(); } public void print( boolean b ) { if ( _chatty ) { super.print( b ); } } public void print( char c ) { if ( _chatty ) { super.print( c ); } } public void print( int i ) { if ( _chatty ) { super.print( i ); } } public void print( long l ) { if ( _chatty ) { super.print( l ); } } public void print( float f ) { if ( _chatty ) { super.print( f ); } } public void print( double d ) { if ( _chatty ) { super.print( d ); } } public void print( char[] s ) { if ( _chatty ) { super.print( s ); } } public void print( String s ) { if ( _chatty ) { super.print( s ); } } public void print( Object obj ) { if ( _chatty ) { super.print( obj ); } } public void println() { if ( _chatty ) { super.println(); } } public void println( boolean x ) { if ( _chatty ) { super.println( x ); } } public void println( char x ) { if ( _chatty ) { super.println( x ); } } public void println( int x ) { if ( _chatty ) { super.println( x ); } } public void println( long x ) { if ( _chatty ) { super.println( x ); } } public void println( float x ) { if ( _chatty ) { super.println( x ); } } public void println( double x ) { if ( _chatty ) { super.println( x ); } } public void println( char[] x ) { if ( _chatty ) { super.println( x ); } } public void println( String x ) { if ( _chatty ) { super.println( x ); } } public void println( Object x ) { if ( _chatty ) { super.println( x ); } } public PrintStream printf( String format, Object... args ) { if ( _chatty ) { super.printf( format, args ); } return this; } public PrintStream printf( Locale l, String format, Object... args ) { if ( _chatty ) { super.printf( l, format, args ); } return this; } public PrintStream format( String format, Object... args ) { if ( _chatty ) { super.format( format, args ); } return this; } public PrintStream format( Locale l, String format, Object... args ) { if ( _chatty ) { super.format( l, format, args ); } return this; } public void write( byte[] buf, int off, int len ) { if ( _chatty ) { super.write( buf, off, len ); } } public void write( int b ) { if ( _chatty ) { super.write( b ); } } } |
blob | data class | t | t | f | data class | blob | 0 | 2549 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.tests/org/apache/derbyTesting/system/nstest/NsTestPrintStream.java/#L31-L127 | 1 | 233 | 2549 | minor |
| 645 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 6363 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 | 1 | 645 | 6363 | critical |
| 2412 | YES I found bad smells 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional logic 5. Many if-else statements 6. Lack of encapsulation/abstraction 7. Inefficient data structures (e.g. using ArrayList instead of Set) 8. Poor error handling (e.g. throwing raw exceptions instead of specific ones) 9. Mixing of concerns (e.g. unmarshaling and setting parameters in the same method) 10. Poor naming conventions (e.g. params, list, xpathList) 11. Magic numbers/strings (e.g. filterVal strings) 12. Multiple responsibility (e.g. handling both init and marshalParams) 13. Inappropriate use of inheritance (e.g. extending from ApacheTransform) 14. Lack of separation of concerns (e.g. transforming and marshaling parameters) 15. Lack of abstraction/reusability (e.g. hardcoded namespaces) 16. Violation of single responsibility principle (e.g. checking for parent class and throwing exception) 17. Insufficient comments/documentations. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Complex conditional logic5 Many if-else statements6 Lack of encapsulation/abstraction7 Inefficient data structures (eg using ArrayList instead of Set)8 Poor error handling (eg throwing raw exceptions instead of specific ones)9 Mixing of concerns (eg unmarshaling and setting parameters in the same method) | t | f | f | . Long method2. Feature envy3. Duplicate code4. Complex conditional logic5. Many if-else statements6. Lack of encapsulation/abstraction7. Inefficient data structures (e.g. using ArrayList instead of Set)8. Poor error handling (e.g. throwing raw exceptions instead of specific ones)9. Mixing of concerns (e.g. unmarshaling and setting parameters in the same method) | blob | 0 | 14403 | https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 | 2 | 2412 | 14403 | major |
| 1550 | found. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11264 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 1550 | 11264 | major | ||
| 1234 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10369 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 1234 | 10369 | minor |
| 655 | {"response":"YES I found bad smells","bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6404 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 1 | 655 | 6404 | major |
| 562 | { "response": "YES I found bad smells", "detected_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean mkdirs( ) { return file.mkdirs( ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5666 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/fs/LocalFile.java/#L80-L84 | 1 | 562 | 5666 | major |
| 1968 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 12604 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 1 | 1968 | 12604 | critical |
| 1436 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | Not specified | f | f | f | false | 0 | 10962 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 1436 | 10962 | minor | |
| 2648 | YES I found bad smells. The bad smells are: 1. Long method - connectWithTimeout() 2. Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } } |
data class | Long method - connectWithTimeout()2 Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | t | f | f | . Long method - connectWithTimeout()2. Feature envy - connectWithTimeout() and Log(), SysLog(), getPort(), getAddress(), isValid(), isOpen() | data class | 0 | 15162 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 | 2 | 2648 | 15162 | minor |
| 4513 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11975 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 4513 | 11975 | minor |
| 2468 | { "output": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | blob | t | t | f | blob | data class | 0 | 14570 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 1 | 2468 | 14570 | minor |
| 3521 | , I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/contentassist/antlr/internal/InternalN4JSParser.java/#L181223-L181248 | 2 | 3521 | 7615 | minor | ||
| 2210 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 13520 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 2 | 2210 | 13520 | major |
| 2451 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14506 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2451 | 14506 | minor |
| 2403 | "NO, I did not find any bad smell". | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14383 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 2 | 2403 | 14383 | minor | ||
| 2261 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13717 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 2261 | 13717 | major |
| 305 | {"message": "YES I found bad smells", "bad smells are:": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 3185 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 305 | 3185 | minor |
| 2336 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate Code 4. Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | Long method2 Feature envy3 Duplicate Code4 Conditional complexity | t | f | f | . Long method2. Feature envy3. Duplicate Code4. Conditional complexity | data class | 0 | 14164 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 2 | 2336 | 14164 | major |
| 4631 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12359 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 4631 | 12359 | minor | ||
| 2865 | YES, I found bad smells. The bad smells are: 1. No comments or documentation present. 2. Inconsistent indentation and formatting. 3. Unused imports. 4. Unnecessary use of serializable. 5. Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | No comments or documentation present2 Inconsistent indentation and formatting3 Unused imports4 Unnecessary use of serializable5 Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods | t | f | f | . No comments or documentation present.2. Inconsistent indentation and formatting.3. Unused imports.4. Unnecessary use of serializable.5. Lack of validation for getTargetRepositoryId() and setTargetRepositoryId() methods. | data class | 0 | 1975 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 2 | 2865 | 1975 | minor |
| 1602 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static final class SymbolComparator implements Comparator { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object arg0, Object arg1) { long addr0=0; long addr1=0; // arg0 and arg1 will be Symbol objects if (arg0 instanceof Symbol) { Symbol S0 = (Symbol) arg0; Symbol S1 = (Symbol) arg1; addr0 = S0.symbolStart; addr1 = S1.symbolStart; } else { addr0 = ((Long)arg0).longValue(); addr1 = ((Long)arg1).longValue(); } // both +ve if (addr0 >= 0 && addr1 >=0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return -1; return 1; } // both -ve if (addr0 < 0 && addr1 < 0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return 1; return -1; } if (addr0 < 0 && addr1 >=0) { return 1; } return -1; } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 11430 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/Symbol.java/#L134-L175 | 1 | 1602 | 11430 | minor |
| 3976 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
blob | long method | t | t | f | long method | blob | 0 | 10433 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 3976 | 10433 | minor |
| 2402 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14382 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 2402 | 14382 | major |
| 1676 | YES I found bad smells the bad smells are: 1. Repetitive code 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
feature envy | Repetitive code2 Long method | t | f | f | . Repetitive code2. Long method | feature envy | 0 | 11645 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 1676 | 11645 | minor |
| 2410 | { "output": "YES I found bad smells", "bad smells are": "1. Long method", "2. Data class" : [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14393 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 1 | 2410 | 14393 | major |
| 2392 | YES I found bad smells The bad smells are: 1. Feature envy (TwitterPullRecordReader relies heavily on accessing external classes and methods, indicating a potential violation of the principle of encapsulation). 2. Long method (the next() method contains many lines of code, indicating a lack of method decomposition and potential for high complexity). 3. Primitive obsession (the use of primitive data types like int and long instead of objects to represent data). 4. Lazy class (the TwitterPullRecordReader class does not have much functionality, indicating it may not be necessary or could be merged with another class). 5. Magic numbers (the values for requestInterval and count are hardcoded, making the code less flexible and readable). 6. Empty methods (the close(), setFeedLogManager(), setController() methods do not have any functionality, indicating potential for dead code). 7. Empty catch statement (the handleException() method catches an exception but does not handle it, potentially leading to hidden bugs). 8. Inconsistent naming convention (the use of abbreviated variable names like tw and th in the next() and handleException() methods). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
blob | Feature envy (TwitterPullRecordReader relies heavily on accessing external classes and methods, indicating a potential violation of the principle of encapsulation)2 Long method (the next() method contains many lines of code, indicating a lack of method decomposition and potential for high complexity)3 Primitive obsession (the use of primitive data types like int and long instead of objects to represent data)4 Lazy class (the TwitterPullRecordReader class does not have much functionality, indicating it may not be necessary or could be merged with another class)5 Magic numbers (the values for requestInterval and count are hardcoded, making the code less flexible and readable)6 Empty methods (the close(), setFeedLogManager(), setController() methods do not have any functionality, indicating potential for dead code)7 Empty catch statement (the handleException() method catches an exception but does not handle it, potentially leading to hidden bugs)8 Inconsistent naming convention (the use of abbreviated variable names like tw and th in the next() and handleException() methods) | t | f | f | . Feature envy (TwitterPullRecordReader relies heavily on accessing external classes and methods, indicating a potential violation of the principle of encapsulation).2. Long method (the next() method contains many lines of code, indicating a lack of method decomposition and potential for high complexity).3. Primitive obsession (the use of primitive data types like int and long instead of objects to represent data).4. Lazy class (the TwitterPullRecordReader class does not have much functionality, indicating it may not be necessary or could be merged with another class).5. Magic numbers (the values for requestInterval and count are hardcoded, making the code less flexible and readable).6. Empty methods (the close(), setFeedLogManager(), setController() methods do not have any functionality, indicating potential for dead code).7. Empty catch statement (the handleException() method catches an exception but does not handle it, potentially leading to hidden bugs).8. Inconsistent naming convention (the use of abbreviated variable names like tw and th in the next() and handleException() methods). | blob | 0 | 14363 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 2 | 2392 | 14363 | minor |
| 1100 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void processRTTmeasurement(long measuredRTT, Exchange exchange, int retransmissionCount){ //System.out.println("Measured an RTT of " + measuredRTT + " after using " + retransmissionCount + " retries." ); RemoteEndpoint endpoint = getRemoteEndpoint(exchange); int rtoType = endpoint.getExchangeEstimatorState(exchange); // The basic rto algorithm does not care for the blind estimator, set weak/strong to false endpoint.setBlindStrong(false); endpoint.setBlindWeak(false); //Perform normal update of the RTO updateEstimator(measuredRTT, rtoType, endpoint); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9830 | https://github.com/eclipse/californium/blob/0dd6db579be90c514dd765027ec55ed7a4668337/californium-core/src/main/java/org/eclipse/californium/core/network/stack/congestioncontrol/BasicRto.java/#L40-L52 | 1 | 1100 | 9830 | minor |
| 422 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 4246 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 422 | 4246 | minor |
| 610 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 6126 | https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 | 2 | 610 | 6126 | minor |
| 1929 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12452 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 1929 | 12452 | major |
| 338 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy (getters and setters) 3. Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | Long method2 Feature envy (getters and setters)3 Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | t | f | f | . Long method2. Feature envy (getters and setters)3. Primitive obsession (declaring lists and hashmaps instead of creating custom objects) | data class | 0 | 3483 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 2 | 338 | 3483 | critical |
| 271 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
blob | Not specified | f | f | f | false | 0 | 2918 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 2 | 271 | 2918 | minor | |
| 4928 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13480 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 2 | 4928 | 13480 | minor |
| 212 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2323 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 2 | 212 | 2323 | minor |
| 820 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LibraryBreadcrumbNodeProvider extends DesignerBreadcrumbNodeProvider { public boolean validate( Object element ) { if ( getEditPart( element ) == null // || getEditPart( element ) instanceof EmptyEditPart ) return false; return true; } public EditPart getEditPart( Object element ) { // EditPart editPart = super.getEditPart( element ); // if ( editPart == null || editPart instanceof EmptyEditPart ) // return null; return super.getEditPart( element ); } @Override public Object[] getChildren( Object element ) { if ( getRealModel( element ) instanceof LibraryHandle ) { return ( (LibraryHandle) getRealModel( element ) ).getComponents( ) .getContents( ) .toArray( ); } List children = new ArrayList( ); children.addAll( Arrays.asList( super.getChildren( element ) ) ); for ( int i = 0; i < children.size( ); i++ ) { if ( children.get( i ) instanceof EmptyEditPart ) { children.remove( i ); i--; } } return children.toArray( ); } @Override public String getText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeDisplayName( object ); } } return super.getText( element ); } @Override public Image getImage( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return null; return provider.getNodeIcon( object ); } } return super.getImage( element ); } @Override public String getTooltipText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeTooltip( object ); } } return super.getTooltipText( element ); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7679 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.lib/src/org/eclipse/birt/report/designer/internal/lib/providers/LibraryBreadcrumbNodeProvider.java/#L31-L127 | 2 | 820 | 7679 | major |
| 2603 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Data class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 15024 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 1 | 2603 | 15024 | major |
| 765 | YES I found bad smells The bad smells are: 1. Magic number (4) in the constructor 2. Empty method (orderItems()) 3. Unused parameter (file) in the constructor 4. Feature envy (calling methods from HeaderItem instead of using getters) 5. Unused field (list) is never modified or accessed in the class except in the "items()" method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class HeaderSection extends UniformItemSection { /** {@code non-null;} the list of the one item in the section */ private final List list; /** * Constructs an instance. The file offset is initially unknown. * * @param file {@code non-null;} file that this instance is part of */ public HeaderSection(DexFile file) { super(null, file, 4); HeaderItem item = new HeaderItem(); item.setIndex(0); this.list = Collections.singletonList(item); } /** {@inheritDoc} */ @Override public IndexedItem get(Constant cst) { return null; } /** {@inheritDoc} */ @Override public Collection items() { return list; } /** {@inheritDoc} */ @Override protected void orderItems() { // Nothing to do here. } } |
data class | Magic number (4) in the constructor2 Empty method (orderItems())3 Unused parameter (file) in the constructor4 Feature envy (calling methods from HeaderItem instead of using getters)5 Unused field (list) is never modified or accessed in the class except in the "items()" method | t | f | f | . Magic number (4) in the constructor2. Empty method (orderItems())3. Unused parameter (file) in the constructor4. Feature envy (calling methods from HeaderItem instead of using getters)5. Unused field (list) is never modified or accessed in the class except in the "items()" method | data class | 0 | 7136 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/HeaderSection.java/#L27-L62 | 2 | 765 | 7136 | minor |
| 1803 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | t | f | f | data class | 0 | 12021 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 1803 | 12021 | major | ||
| 2664 | { "response": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 15200 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 1 | 2664 | 15200 | minor |
| 1284 | YES I found bad smells the bad smells are: 1. Conditional complexity 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | Conditional complexity 2 Long method | t | f | f | . Conditional complexity 2. Long method | feature envy | 0 | 10606 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 1284 | 10606 | major |
| 3579 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7895 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 1 | 3579 | 7895 | critical |
| 1097 | { "message": "YES, I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 9800 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 1 | 1097 | 9800 | minor |
| 1418 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 10924 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1418 | 10924 | minor |
| 1256 | {"response": "YES I found bad smells", "detected_bad_smells": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } } |
blob | 2. data class | t | t | f | 2. data class | blob | 0 | 10494 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 | 1 | 1256 | 10494 | minor |
| 2576 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14917 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 2 | 2576 | 14917 | minor |
| 1137 | { "output": "YES, I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | "YES, I found bad smells", "the bad smells are" | t | f | f | "YES, I found bad smells", "the bad smells are" | data class | 0 | 10065 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 1137 | 10065 | minor |
| 80 | { "response": "YES I found bad smells", "bad smells are": [ "1.Long method", "2.Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | data class | 0 | 1185 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 80 | 1185 | critical |
| 463 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PKWareExtraHeader implements ZipExtraField { private final ZipShort headerId; /** * Extra field data in local file data - without Header-ID or length * specifier. */ private byte[] localData; /** * Extra field data in central directory - without Header-ID or length * specifier. */ private byte[] centralData; protected PKWareExtraHeader(final ZipShort headerId) { this.headerId = headerId; } /** * Get the header id. * * @return the header id */ @Override public ZipShort getHeaderId() { return headerId; } /** * Set the extra field data in the local file data - without Header-ID or * length specifier. * * @param data * the field data to use */ public void setLocalFileDataData(final byte[] data) { localData = ZipUtil.copy(data); } /** * Get the length of the local data. * * @return the length of the local data */ @Override public ZipShort getLocalFileDataLength() { return new ZipShort(localData != null ? localData.length : 0); } /** * Get the local data. * * @return the local data */ @Override public byte[] getLocalFileDataData() { return ZipUtil.copy(localData); } /** * Set the extra field data in central directory. * * @param data * the data to use */ public void setCentralDirectoryData(final byte[] data) { centralData = ZipUtil.copy(data); } /** * Get the central data length. If there is no central data, get the local * file data length. * * @return the central data length */ @Override public ZipShort getCentralDirectoryLength() { if (centralData != null) { return new ZipShort(centralData.length); } return getLocalFileDataLength(); } /** * Get the central data. * * @return the central data if present, else return the local file data */ @Override public byte[] getCentralDirectoryData() { if (centralData != null) { return ZipUtil.copy(centralData); } return getLocalFileDataData(); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromLocalFileData(byte[], int, int) */ @Override public void parseFromLocalFileData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setLocalFileDataData(tmp); } /** * @param data * the array of bytes. * @param offset * the source location in the data array. * @param length * the number of bytes to use in the data array. * @see ZipExtraField#parseFromCentralDirectoryData(byte[], int, int) */ @Override public void parseFromCentralDirectoryData(final byte[] data, final int offset, final int length) { final byte[] tmp = new byte[length]; System.arraycopy(data, offset, tmp, 0, length); setCentralDirectoryData(tmp); if (localData == null) { setLocalFileDataData(tmp); } } /** * Encryption algorithm. * * @since 1.11 */ public enum EncryptionAlgorithm { DES(0x6601), RC2pre52(0x6602), TripleDES168(0x6603), TripleDES192(0x6609), AES128(0x660E), AES192(0x660F), AES256(0x6610), RC2(0x6702), RC4(0x6801), UNKNOWN(0xFFFF); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final EncryptionAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ EncryptionAlgorithm(final int code) { this.code = code; } /** * the algorithm id. * * @return the PKWare AlgorithmId */ public int getCode() { return code; } /** * Returns the EncryptionAlgorithm for the given code or null if the * method is not known. * @param code the code of the algorithm * @return the EncryptionAlgorithm for the given code or null * if the method is not known */ public static EncryptionAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } /** * Hash Algorithm * * @since 1.11 */ public enum HashAlgorithm { NONE(0), CRC32(1), MD5(0x8003), SHA1(0x8004), RIPEND160(0x8007), SHA256(0x800C), SHA384(0x800D), SHA512(0x800E); private final int code; private static final Map codeToEnum; static { final Map cte = new HashMap<>(); for (final HashAlgorithm method : values()) { cte.put(method.getCode(), method); } codeToEnum = Collections.unmodifiableMap(cte); } /** * private constructor for enum style class. */ HashAlgorithm(final int code) { this.code = code; } /** * the hash algorithm ID. * * @return the PKWare hashAlg */ public int getCode() { return code; } /** * Returns the HashAlgorithm for the given code or null if the method is * not known. * @param code the code of the algorithm * @return the HashAlgorithm for the given code or null * if the method is not known */ public static HashAlgorithm getAlgorithmByCode(final int code) { return codeToEnum.get(code); } } } |
data class | blob, feature envy | t | t | f | blob, feature envy | data class | 0 | 4487 | https://github.com/apache/commons-compress/blob/1881a202fbec4466f3766eaa0057370d7007401b/src/main/java/org/apache/commons/compress/archivers/zip/PKWareExtraHeader.java/#L66-L308 | 1 | 463 | 4487 | minor |
| 223 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TemporalIntervalStartDatetimeAccessor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; private static final FunctionIdentifier FID = BuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_START_DATETIME; public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new TemporalIntervalStartDatetimeAccessor(); } }; @Override public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IScalarEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IScalarEvaluator createScalarEvaluator(IHyracksTaskContext ctx) throws HyracksDataException { return new IScalarEvaluator() { private final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage(); private final DataOutput out = resultStorage.getDataOutput(); private final IPointable argPtr = new VoidPointable(); private final IScalarEvaluator eval = args[0].createScalarEvaluator(ctx); // possible output @SuppressWarnings("unchecked") private final ISerializerDeserializer datetimeSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADATETIME); private final AMutableDateTime aDateTime = new AMutableDateTime(0); @Override public void evaluate(IFrameTupleReference tuple, IPointable result) throws HyracksDataException { eval.evaluate(tuple, argPtr); byte[] bytes = argPtr.getByteArray(); int startOffset = argPtr.getStartOffset(); resultStorage.reset(); try { if (bytes[startOffset] == ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG) { byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes, startOffset + 1); long startTime = AIntervalSerializerDeserializer.getIntervalStart(bytes, startOffset + 1); if (timeType == ATypeTag.SERIALIZED_DATETIME_TYPE_TAG) { aDateTime.setValue(startTime); datetimeSerde.serialize(aDateTime, out); } else { throw new InvalidDataFormatException(sourceLoc, getIdentifier(), ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } else { throw new TypeMismatchException(sourceLoc, getIdentifier(), 0, bytes[startOffset], ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } catch (IOException e) { throw HyracksDataException.create(e); } result.set(resultStorage); } }; } }; } /* (non-Javadoc) * @see org.apache.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2416 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/accessors/TemporalIntervalStartDatetimeAccessor.java/#L47-L119 | 1 | 223 | 2416 | major |
| 1908 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 12396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 1908 | 12396 | major |
| 1184 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class LdapProtocolUtils { /** A delimiter for the replicaId */ public static final String COOKIE_DELIM = ","; /** the prefix for replicaId value */ public static final String REPLICA_ID_PREFIX = "rid="; public static final int REPLICA_ID_PREFIX_LEN = REPLICA_ID_PREFIX.length(); /** the prefix for Csn value */ public static final String CSN_PREFIX = "csn="; private static final int CSN_PREFIX_LEN = CSN_PREFIX.length(); private static final Logger LOG = LoggerFactory.getLogger( LdapProtocolUtils.class ); private LdapProtocolUtils() { } /** * Extracts request controls from a request to populate into an * OperationContext. * * @param opContext the context to populate with request controls * @param request the request to extract controls from */ public static void setRequestControls( OperationContext opContext, Request request ) { if ( request.getControls() != null ) { opContext .addRequestControls( request.getControls().values().toArray( LdapProtocolConstants.EMPTY_CONTROLS ) ); } } /** * Extracts response controls from a an OperationContext to populate into * a Response object. * * @param opContext the context to extract controls from * @param response the response to populate with response controls */ public static void setResponseControls( OperationContext opContext, Response response ) { response.addAllControls( opContext.getResponseControls() ); } public static byte[] createCookie( int replicaId, String csn ) { // the syncrepl cookie format (compatible with OpenLDAP) // rid=nn,csn=xxxz String replicaIdStr = StringUtils.leftPad( Integer.toString( replicaId ), 3, '0' ); return Strings.getBytesUtf8( REPLICA_ID_PREFIX + replicaIdStr + COOKIE_DELIM + CSN_PREFIX + csn ); } /** * Check the cookie syntax. A cookie must have the following syntax : * { rid={replicaId},csn={CSN} } * * @param cookieString The cookie * @return true if the cookie is valid */ public static boolean isValidCookie( String cookieString ) { if ( ( cookieString == null ) || ( cookieString.trim().length() == 0 ) ) { return false; } int pos = cookieString.indexOf( COOKIE_DELIM ); // position should start from REPLICA_ID_PREFIX_LEN or higher cause a cookie can be // like "rid=0,csn={csn}" or "rid=11,csn={csn}" if ( pos <= REPLICA_ID_PREFIX_LEN ) { return false; } String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, pos ); try { Integer.parseInt( replicaId ); } catch ( NumberFormatException e ) { LOG.debug( "Failed to parse the replica id {}", replicaId ); return false; } if ( pos == cookieString.length() ) { return false; } String csnString = cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); return Csn.isValid( csnString ); } /** * returns the CSN present in cookie * * @param cookieString the cookie * @return The CSN */ public static String getCsn( String cookieString ) { int pos = cookieString.indexOf( COOKIE_DELIM ); return cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); } /** * returns the replica id present in cookie * * @param cookieString the cookie * @return The replica Id */ public static int getReplicaId( String cookieString ) { String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, cookieString.indexOf( COOKIE_DELIM ) ); return Integer.parseInt( replicaId ); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 10239 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolUtils.java/#L38-L171 | 2 | 1184 | 10239 | minor |
| 555 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 5607 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 555 | 5607 | critical |
| 207 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 2307 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 | 1 | 207 | 2307 | major |
| 896 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Value @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Argument { public static Argument SKIP_TESTS = Argument.arg("skipTests"); @NonNull String name; @NonNull Optional> value; private Argument(String name, ArgumentValue value) { this(name, Optional.of(value)); } static Argument of(String name) { return new Argument(name, Optional.empty()); } /** * Enables the given comma-separated profiles for the {@link CommandLine}. * * @param name must not be {@literal null} or empty. * @return */ public static Argument profile(String name, String... others) { Assert.hasText(name, "Profiles must not be null or empty!"); Assert.notNull(others, "Other profiles must not be null!"); String profiles = Stream.concat(Stream.of(name), Arrays.stream(others)).collect(Collectors.joining(",")); return Argument.of("-P".concat(profiles)); } public static Argument arg(String name) { return Argument.of("-D".concat(name)); } public static Argument debug() { return Argument.of("-X"); } public Argument withValue(Object value) { return new Argument(name, ArgumentValue.of(value)); } public Argument withQuotedValue(Object value) { return new Argument(name, ArgumentValue.of(value, it -> String.format("\"%s\"", it.toString()))); } public Argument withValue(Masked masked) { return new Argument(name, ArgumentValue.of(masked)); } public String toCommandLineArgument() { return toNameValuePair(value.map(ArgumentValue::toCommandLine)); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return toNameValuePair(value.map(Object::toString)); } private String toNameValuePair(Optional source) { return source// .map(it -> String.format("%s=%s", name, it))// .orElse(name); } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class ArgumentValue { private final @NonNull T value; private final @NonNull Optional> preparer; private final @NonNull Optional> toString; public static ArgumentValue of(T value) { return new ArgumentValue<>(value, Optional.empty(), Optional.empty()); } public static ArgumentValue of(T value, Function preparer) { return new ArgumentValue<>(value, Optional.of(preparer), Optional.empty()); } /** * Returns an {@link ArgumentValue} for the given {@link Masked} value. * * @param masked must not be {@literal null}. * @return */ public static ArgumentValue of(T masked) { return new ArgumentValue<>(masked, Optional.empty(), Optional.of(it -> it.masked())); } /** * Returns the {@link String} variant of the argument value. * * @return */ public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return toString.map(it -> it.apply(value)).orElseGet(() -> toCommandLine()); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 8137 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L142-L257 | 1 | 896 | 8137 | minor |
| 2700 | {"response": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 15327 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 2 | 2700 | 15327 | minor |
| 56 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MapImageLayerTablesSample extends Application { private MapView mapView; private GraphicsOverlay graphicsOverlay; private ServiceFeatureTable commentsTable; private ListView commentsListView; /** * Starting point of this application. * * @param args arguments to this application. */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { // create a stack pane and application scene StackPane stackPane = new StackPane(); Scene scene = new Scene(stackPane); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); // size the stage and add a title stage.setTitle("Map Image Layer Tables Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(scene); stage.show(); // create a map with a basemap ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); // create and add a map image layer to the map // the map image layer contains a feature table with related spatial and non-spatial comment features ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer"); map.getOperationalLayers().add(imageLayer); // create a map view and set the map to it mapView = new MapView(); mapView.setMap(map); // create a graphics overlay to show the related spatial features in graphicsOverlay = new GraphicsOverlay(); mapView.getGraphicsOverlays().add(graphicsOverlay); // show the related graphics as cyan circles SimpleRenderer renderer = new SimpleRenderer(); renderer.setSymbol(new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF00FFFF, 14)); graphicsOverlay.setRenderer(renderer); // create a list view to show the non-spatial comment features commentsListView = new ListView<>(); commentsListView.setMaxSize(200.0, 150.0); // show the comments attribute of the feature in the list commentsListView.setCellFactory(listView -> new ListCell() { @Override protected void updateItem(Feature item, boolean empty) { super.updateItem(item, empty); if (item != null) { ArcGISFeature feature = (ArcGISFeature) item; setText((String) feature.getAttributes().get("comments")); } } }); // when a comment is selected, query its related spatial features and show the first result on the map commentsListView.getSelectionModel().selectedItemProperty().addListener(observable -> showRelatedRequests()); // when the layer is loaded, get the comment features imageLayer.addDoneLoadingListener(() -> { if (imageLayer.getLoadStatus() == LoadStatus.LOADED) { // zoom to the layer's extent mapView.setViewpoint(new Viewpoint(imageLayer.getFullExtent())); // get the comments feature table commentsTable = imageLayer.getTables().get(0); // create query parameters to get features that have non-empty comments QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause("requestid <> '' AND comments <> ''"); // query the comments table for features ListenableFuture featureQuery = commentsTable.queryFeaturesAsync(queryParameters); featureQuery.addDoneListener(() -> { try { // add the returned features to the list view FeatureQueryResult results = featureQuery.get(); for (Feature f : results) { commentsListView.getItems().addAll(f); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Error querying comment features"); } }); } else { new Alert(Alert.AlertType.ERROR, imageLayer.getLoadError().getMessage()).show(); } }); // add the mapview and controls to the stack pane stackPane.getChildren().addAll(mapView, commentsListView); StackPane.setAlignment(commentsListView, Pos.TOP_LEFT); StackPane.setMargin(commentsListView, new Insets(10, 0, 0, 10)); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } /** * Queries for spatial features related to the selected comment in the list view and shows the first result on the * map as a graphic. */ private void showRelatedRequests() { // clear any previous results graphicsOverlay.getGraphics().clear(); // get the selected comment feature from the list view Feature selectedCommentFeature = commentsListView.getSelectionModel().getSelectedItem(); if (selectedCommentFeature != null) { // get the relationships info between layers in the table ArcGISFeature feature = (ArcGISFeature) selectedCommentFeature; List relationshipInfos = commentsTable.getLayerInfo().getRelationshipInfos(); if (!relationshipInfos.isEmpty()) { // use the first relationship for the related query parameters RelationshipInfo commentsRelationshipInfo = relationshipInfos.get(0); RelatedQueryParameters relatedQueryParameters = new RelatedQueryParameters(commentsRelationshipInfo); relatedQueryParameters.setReturnGeometry(true); // query the table for related features using the parameters ListenableFuture> relatedFeaturesRequest = commentsTable .queryRelatedFeaturesAsync(feature, relatedQueryParameters); relatedFeaturesRequest.addDoneListener(() -> { try { // loop through the returned related features List results = relatedFeaturesRequest.get(); if (!results.isEmpty()) { RelatedFeatureQueryResult relatedResult = results.get(0); if (relatedResult.iterator().hasNext()) { // get the first related feature ArcGISFeature relatedFeature = (ArcGISFeature) relatedResult.iterator().next(); // load the feature and get its geometry to show as a graphic on the map relatedFeature.loadAsync(); relatedFeature.addDoneLoadingListener(() -> { if (relatedFeature.getLoadStatus() == LoadStatus.LOADED) { Point point = (Point) relatedFeature.getGeometry(); Graphic graphic = new Graphic(point); graphicsOverlay.getGraphics().add(graphic); // zoom to the graphic mapView.setViewpointCenterAsync(point, 40000); } }); } } else { new Alert(Alert.AlertType.INFORMATION, "No related features found").show(); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Failed to query relationships").show(); } }); } } } @Override public void stop() { // releases resources when the application closes if (mapView != null) { mapView.dispose(); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 976 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/imagelayers/map_image_layer_tables/MapImageLayerTablesSample.java/#L53-L234 | 1 | 56 | 976 | major |
| 4062 | {"message": "YES, I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10721 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 | 1 | 4062 | 10721 | major |
| 264 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2866 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 1 | 264 | 2866 | minor |
| 315 | {"response":"YES I found bad smells","bad smells are":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3235 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 1 | 315 | 3235 | minor |
| 1377 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10811 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 2 | 1377 | 10811 | minor |
| 1894 | //'and' public Group getGroup_1() { return cGroup_1; } //'and' public Group getGroup_1_0() { return cGroup_1_0; } // {BinaryLogicalExpression.lhs=current} public Group getGroup_1_0_0() { return cGroup_1_0_0; } //=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Action getBinaryLogicalExpressionLhsAction_1_0_0_0() { return cBinaryLogicalExpressionLhsAction_1_0_0_0; } //op=LogicalANDOperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //LogicalANDOperator public RuleCall getOpLogicalANDOperatorParserRuleCall_1_0_0_1_0() { return cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0; } public class LogicalANDOperatorElements extends AbstractParserRuleElementFinder { YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
blob | () { return cGroup_ | t | f | f | () { return cGroup_ | blob | 0 | 12321 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 1894 | 12321 | minor |
| 768 | YES I found bad smells the bad smell is: Feature envy, Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | Feature envy, Long method | t | f | f | Feature envy, Long method | blob | 0 | 7237 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 2 | 768 | 7237 | minor |
| 1974 | {"output": "YES, I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({ "unchecked", "rawtypes" }) public final class CorePlugin extends Plugin { public static final String PLUGIN_ID = "org.eclipse.buildship.core"; //$NON-NLS-1$ public static final String GRADLE_JOB_FAMILY = PLUGIN_ID + ".jobs"; private static CorePlugin plugin; // do not use generics-aware signature since this causes compilation troubles (JDK, Spock) // search the web for -target jsr14 to find out more about this obscurity private ServiceRegistration loggerService; private ServiceRegistration publishedGradleVersionsService; private ServiceRegistration workspaceOperationsService; private ServiceRegistration internalGradleWorkspaceService; private ServiceRegistration processStreamsProviderService; private ServiceRegistration gradleLaunchConfigurationService; private ServiceRegistration listenerRegistryService; // service tracker for each service to allow to register other service implementations of the // same type but with higher prioritization, useful for testing private ServiceTracker loggerServiceTracker; private ServiceTracker publishedGradleVersionsServiceTracker; private ServiceTracker workspaceOperationsServiceTracker; private ServiceTracker internalGradleWorkspaceServiceTracker; private ServiceTracker processStreamsProviderServiceTracker; private ServiceTracker gradleLaunchConfigurationServiceTracker; private ServiceTracker listenerRegistryServiceTracker; private DefaultModelPersistence modelPersistence; private ProjectChangeListener projectChangeListener; private SynchronizingBuildScriptUpdateListener buildScriptUpdateListener; private InvocationCustomizer invocationCustomizer; private ConfigurationManager configurationManager; private DefaultExternalLaunchConfigurationManager externalLaunchConfigurationManager; private ToolingApiOperationManager operationManager; private ExtensionManager extensionManager; @Override public void start(BundleContext bundleContext) throws Exception { super.start(bundleContext); plugin = this; ensureProxySettingsApplied(); registerServices(bundleContext); } @Override public void stop(BundleContext context) throws Exception { unregisterServices(); plugin = null; super.stop(context); } private void ensureProxySettingsApplied() throws Exception { // the proxy settings are set when the core.net plugin is started Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT); } private void registerServices(BundleContext context) { // store services with low ranking such that they can be overridden // during testing or the like Dictionary preferences = new Hashtable<>(); preferences.put(Constants.SERVICE_RANKING, 1); // initialize service trackers before the services are created this.loggerServiceTracker = createServiceTracker(context, Logger.class); this.publishedGradleVersionsServiceTracker = createServiceTracker(context, PublishedGradleVersionsWrapper.class); this.workspaceOperationsServiceTracker = createServiceTracker(context, WorkspaceOperations.class); this.internalGradleWorkspaceServiceTracker = createServiceTracker(context, InternalGradleWorkspace.class); this.processStreamsProviderServiceTracker = createServiceTracker(context, ProcessStreamsProvider.class); this.gradleLaunchConfigurationServiceTracker = createServiceTracker(context, GradleLaunchConfigurationManager.class); this.listenerRegistryServiceTracker = createServiceTracker(context, ListenerRegistry.class); // register all services this.loggerService = registerService(context, Logger.class, createLogger(), preferences); this.publishedGradleVersionsService = registerService(context, PublishedGradleVersionsWrapper.class, createPublishedGradleVersions(), preferences); this.workspaceOperationsService = registerService(context, WorkspaceOperations.class, createWorkspaceOperations(), preferences); this.internalGradleWorkspaceService = registerService(context, InternalGradleWorkspace.class, createGradleWorkspace(), preferences); this.processStreamsProviderService = registerService(context, ProcessStreamsProvider.class, createProcessStreamsProvider(), preferences); this.gradleLaunchConfigurationService = registerService(context, GradleLaunchConfigurationManager.class, createGradleLaunchConfigurationManager(), preferences); this.listenerRegistryService = registerService(context, ListenerRegistry.class, createListenerRegistry(), preferences); this.modelPersistence = DefaultModelPersistence.createAndRegister(); this.projectChangeListener = ProjectChangeListener.createAndRegister(); this.buildScriptUpdateListener = SynchronizingBuildScriptUpdateListener.createAndRegister(); this.invocationCustomizer = new InvocationCustomizerCollector(); this.configurationManager = new DefaultConfigurationManager(); this.externalLaunchConfigurationManager = DefaultExternalLaunchConfigurationManager.createAndRegister(); this.operationManager = new DefaultToolingApiOperationManager(); this.extensionManager = new DefaultExtensionManager(); } private ServiceTracker createServiceTracker(BundleContext context, Class clazz) { ServiceTracker serviceTracker = new ServiceTracker(context, clazz.getName(), null); serviceTracker.open(); return serviceTracker; } private ServiceRegistration registerService(BundleContext context, Class clazz, T service, Dictionary properties) { return context.registerService(clazz.getName(), service, properties); } private EclipseLogger createLogger() { Map tracingEnablement = Maps.newHashMap(); for (TraceScope scope : CoreTraceScopes.values()) { String option = Platform.getDebugOption("org.eclipse.buildship.core/trace/" + scope.getScopeKey()); tracingEnablement.put(scope, "true".equalsIgnoreCase(option)); } return new EclipseLogger(getLog(), PLUGIN_ID, tracingEnablement); } private PublishedGradleVersionsWrapper createPublishedGradleVersions() { return new PublishedGradleVersionsWrapper(); } private WorkspaceOperations createWorkspaceOperations() { return new DefaultWorkspaceOperations(); } private InternalGradleWorkspace createGradleWorkspace() { return new DefaultGradleWorkspace(); } private ProcessStreamsProvider createProcessStreamsProvider() { return new StdProcessStreamsProvider(); } private GradleLaunchConfigurationManager createGradleLaunchConfigurationManager() { return new DefaultGradleLaunchConfigurationManager(); } private ListenerRegistry createListenerRegistry() { return new DefaultListenerRegistry(); } private void unregisterServices() { this.externalLaunchConfigurationManager.unregister(); this.buildScriptUpdateListener.close(); this.projectChangeListener.close(); this.modelPersistence.close(); this.listenerRegistryService.unregister(); this.gradleLaunchConfigurationService.unregister(); this.processStreamsProviderService.unregister(); this.internalGradleWorkspaceService.unregister(); this.workspaceOperationsService.unregister(); this.publishedGradleVersionsService.unregister(); this.loggerService.unregister(); this.listenerRegistryServiceTracker.close(); this.gradleLaunchConfigurationServiceTracker.close(); this.processStreamsProviderServiceTracker.close(); this.internalGradleWorkspaceServiceTracker.close(); this.workspaceOperationsServiceTracker.close(); this.publishedGradleVersionsServiceTracker.close(); this.loggerServiceTracker.close(); } public static CorePlugin getInstance() { return plugin; } public static Logger logger() { return (Logger) getInstance().loggerServiceTracker.getService(); } public static PublishedGradleVersionsWrapper publishedGradleVersions() { return (PublishedGradleVersionsWrapper) getInstance().publishedGradleVersionsServiceTracker.getService(); } public static WorkspaceOperations workspaceOperations() { return (WorkspaceOperations) getInstance().workspaceOperationsServiceTracker.getService(); } public static InternalGradleWorkspace internalGradleWorkspace() { return (InternalGradleWorkspace) getInstance().internalGradleWorkspaceServiceTracker.getService(); } public static ProcessStreamsProvider processStreamsProvider() { return (ProcessStreamsProvider) getInstance().processStreamsProviderServiceTracker.getService(); } public static GradleLaunchConfigurationManager gradleLaunchConfigurationManager() { return (GradleLaunchConfigurationManager) getInstance().gradleLaunchConfigurationServiceTracker.getService(); } public static ListenerRegistry listenerRegistry() { return (ListenerRegistry) getInstance().listenerRegistryServiceTracker.getService(); } public static ModelPersistence modelPersistence() { return getInstance().modelPersistence; } public static InvocationCustomizer invocationCustomizer() { return getInstance().invocationCustomizer; } public static ConfigurationManager configurationManager() { return getInstance().configurationManager; } public static ExternalLaunchConfigurationManager externalLaunchConfigurationManager() { return getInstance().externalLaunchConfigurationManager; } public static ToolingApiOperationManager operationManager() { return getInstance().operationManager; } public static ExtensionManager extensionManager() { return getInstance().extensionManager; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12619 | https://github.com/eclipse/buildship/blob/3111a7a9fe3e22d6123366686874ecd42aa2a53a/org.eclipse.buildship.core/src/main/java/org/eclipse/buildship/core/internal/CorePlugin.java/#L70-L282 | 1 | 1974 | 12619 | major |
| 1743 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11846 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 2 | 1743 | 11846 | minor |
| 177 | {"message": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2053 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 177 | 2053 | critical |
| 62 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue.Builder public abstract static class Builder { public abstract Builder setCompileTimeConstant(boolean compileTimeConstant); public abstract Builder setStatic(boolean isStatic); public abstract Builder setFinal(boolean isFinal); public abstract Builder setVariableCapture(boolean isVariableCapture); public abstract Builder setEnclosingInstanceCapture(boolean isEnclosingInstanceCapture); public abstract Builder setEnclosingTypeDescriptor( DeclaredTypeDescriptor enclosingTypeDescriptor); public abstract Builder setName(String name); public abstract Builder setEnumConstant(boolean isEnumConstant); public abstract Builder setSynthetic(boolean isSynthetic); public abstract Builder setTypeDescriptor(TypeDescriptor typeDescriptor); public abstract Builder setVisibility(Visibility visibility); public abstract Builder setJsInfo(JsInfo jsInfo); public abstract Builder setUnusableByJsSuppressed(boolean isUnusableByJsSuppressed); public abstract Builder setDeprecated(boolean isDeprecated); public abstract Builder setOrigin(FieldOrigin fieldOrigin); public Builder setDeclarationFieldDescriptor(FieldDescriptor declarationFieldDescriptor) { return setDeclarationFieldDescriptorOrNullIfSelf(declarationFieldDescriptor); } // Accessors to support validation, default construction and custom setters. abstract Builder setDeclarationFieldDescriptorOrNullIfSelf( FieldDescriptor declarationFieldDescriptor); abstract Optional getName(); abstract FieldDescriptor autoBuild(); public FieldDescriptor build() { checkState(getName().isPresent()); FieldDescriptor fieldDescriptor = autoBuild(); checkState( !fieldDescriptor.isVariableCapture() || !fieldDescriptor.isEnclosingInstanceCapture()); return interner.intern(fieldDescriptor); } public static Builder from(FieldDescriptor fieldDescriptor) { return fieldDescriptor.toBuilder(); } private static final ThreadLocalInterner interner = new ThreadLocalInterner<>(); } |
data class | long method, blob | t | t | f | long method, blob | data class | 0 | 1048 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/ast/FieldDescriptor.java/#L194-L255 | 1 | 62 | 1048 | major |
| 2473 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14582 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 1 | 2473 | 14582 | major |
| 1761 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11891 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 1761 | 11891 | critical |
| 243 | {"message": "YES, I found bad smells", "bad_smells": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2648 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 243 | 2648 | critical |
| 1541 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11237 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 2 | 1541 | 11237 | major |
| 2101 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13160 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 1 | 2101 | 13160 | minor |
| 595 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Exceptions { private Exceptions() { } public static IllegalArgumentException propertyKeyCanNotBeEmpty() { return new IllegalArgumentException("Property key can not be the empty string"); } public static IllegalArgumentException propertyKeyCanNotBeNull() { return new IllegalArgumentException("Property key can not be null"); } public static IllegalArgumentException propertyValueCanNotBeNull() { return new IllegalArgumentException("Property value can not be null"); } public static IllegalArgumentException propertyKeyCanNotBeAHiddenKey(final String key) { return new IllegalArgumentException("Property key can not be a hidden key: " + key); } public static IllegalStateException propertyDoesNotExist() { return new IllegalStateException("The property does not exist as it has no key, value, or associated element"); } public static IllegalStateException propertyDoesNotExist(final Element element, final String key) { return new IllegalStateException("The property does not exist as the key has no associated value for the provided element: " + element + ":" + key); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val) { return dataTypeOfPropertyValueNotSupported(val, null); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val, final Exception rootCause) { return new IllegalArgumentException(String.format("Property value [%s] is of type %s is not supported", val, val.getClass()), rootCause); } public static IllegalStateException propertyRemovalNotSupported() { return new IllegalStateException("Property removal is not supported"); } } |
data class | long method | t | t | f | long method | data class | 0 | 5930 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Property.java/#L129-L169 | 1 | 595 | 5930 | major |
| 1098 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9825 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 1098 | 9825 | major |
| 812 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ICEDocCleaner { public static void main(String[] args) throws IOException { // Get a handle on the file System.out.println("Enter full filepath: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String path = br.readLine(); if (path.contains("exit")) { return; } File javaFile = new File(path); if (javaFile != null && javaFile.exists() && javaFile.isFile()) { System.out.println("File found, beginning cleaning..."); FileInputStream inputStream = null; Scanner scanner = null; StringBuilder sb = null; try { // Set up a scanner (should be more efficient than Files.nio for very big files) inputStream = new FileInputStream(javaFile); scanner = new Scanner(inputStream, "UTF-8"); String line = ""; sb = new StringBuilder(); while (scanner.hasNextLine() && (line = scanner.nextLine()) != null) { if (line.matches("\\s*\\*\\s*\\s*") || line.matches("\\s*\\*\\s*\\s*") || line.matches("\\s*// (begin|end)-user-code\\s*") || line.contains("@generated") || line.contains("UML to Java")) { // Skip over the line continue; } else { // Append the line to the StringBuilder sb.append(line + "\n"); } } System.out.println("Done cleaning."); // Note that Scanner suppresses exceptions, throw manually if (scanner.ioException() != null) { throw scanner.ioException(); } } finally { // Close this MF dooown if (inputStream != null) { inputStream.close(); } if (scanner != null) { scanner.close(); } } // Create a backup file in case something goes wrong int fileExtIndex = javaFile.getPath().lastIndexOf("."); String bakFilePath = javaFile.getPath().substring(0, fileExtIndex) + "_bak" + javaFile.getPath().substring(fileExtIndex); File bakFile = new File(bakFilePath); if (bakFile.exists()) { bakFile.delete(); } Files.copy(javaFile.toPath(), bakFile.toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("Creating back-up file... (will delete on successful exit)\n" + bakFile.getPath()); // Overwrite the original file BufferedWriter writer = new BufferedWriter(new FileWriter(javaFile)); writer.write(sb.toString()); System.out.println("Overwriting original file..."); if (writer != null) { writer.close(); } System.out.println("Process complete!"); bakFile.deleteOnExit(); } else { System.out.println("Could not find file."); main(args); } // k bai. return; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7652 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/utils/ICEDocCleaner/src/ICEDocCleaner.java/#L36-L131 | 1 | 812 | 7652 | major |
| 323 | { "output": "YES I found bad smells", "detected_bad_smells": { "1. Long Method": "writeTo method in GridH2DmlResponse class", "2. Long Method": "readFrom method in GridH2DmlResponse class" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
blob | 1. long method: writeto method in gridh2dmlresponse class, 2. long method: readfrom method in gridh2dmlresponse class | t | t | f | 1. long method: writeto method in gridh2dmlresponse class, 2. long method: readfrom method in gridh2dmlresponse class | blob | 0 | 3320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 323 | 3320 | major |
| 285 | { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void securityConfEdited() { // Need to call explicitly since we will not get notified of changes to local security.json cores.securityNodeChanged(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 3055 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/admin/SecurityConfHandlerLocal.java/#L99-L103 | 1 | 285 | 3055 | minor |
| 5764 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 14546 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5764 | 14546 | minor |
| 1596 | { "output": "YES I found bad smells the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | t | f | f | data class | 0 | 11413 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 1596 | 11413 | major | ||
| 317 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract Builder setHosts(List hosts); abstract Builder setPort(Integer port); abstract Builder setKeyspace(String keyspace); abstract Builder setEntity(Class entity); abstract Builder setUsername(String username); abstract Builder setPassword(String password); abstract Builder setLocalDc(String localDc); abstract Builder setConsistencyLevel(String consistencyLevel); abstract Builder setMutationType(MutationType mutationType); abstract Write build(); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 3255 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/CassandraIO.java/#L936-L957 | 2 | 317 | 3255 | major |
| 1464 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11029 | https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 | 1 | 1464 | 11029 | minor |
| 222 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DynamicWebAppClusterImpl extends DynamicClusterImpl implements DynamicWebAppCluster { private static final Logger log = LoggerFactory.getLogger(DynamicWebAppClusterImpl.class); private static final FilenameToWebContextMapper FILENAME_TO_WEB_CONTEXT_MAPPER = new FilenameToWebContextMapper(); /** * Instantiate a new DynamicWebAppCluster. Parameters as per {@link DynamicCluster#DynamicCluster()} */ public DynamicWebAppClusterImpl() { super(); } @Override public void init() { super.init(); // Enricher attribute setup. A way of automatically discovering these (but avoiding // averaging things like HTTP port and response codes) would be neat. List>> summingEnricherSetup = ImmutableList.of( ImmutableList.of(REQUEST_COUNT, REQUEST_COUNT), ImmutableList.of(ERROR_COUNT, ERROR_COUNT), ImmutableList.of(REQUESTS_PER_SECOND_LAST, REQUESTS_PER_SECOND_LAST), ImmutableList.of(REQUESTS_PER_SECOND_IN_WINDOW, REQUESTS_PER_SECOND_IN_WINDOW), ImmutableList.of(TOTAL_PROCESSING_TIME, TOTAL_PROCESSING_TIME), ImmutableList.of(PROCESSING_TIME_FRACTION_IN_WINDOW, PROCESSING_TIME_FRACTION_IN_WINDOW) ); List>> averagingEnricherSetup = ImmutableList.of( ImmutableList.of(REQUEST_COUNT, REQUEST_COUNT_PER_NODE), ImmutableList.of(ERROR_COUNT, ERROR_COUNT_PER_NODE), ImmutableList.of(REQUESTS_PER_SECOND_LAST, REQUESTS_PER_SECOND_LAST_PER_NODE), ImmutableList.of(REQUESTS_PER_SECOND_IN_WINDOW, REQUESTS_PER_SECOND_IN_WINDOW_PER_NODE), ImmutableList.of(TOTAL_PROCESSING_TIME, TOTAL_PROCESSING_TIME_PER_NODE), ImmutableList.of(PROCESSING_TIME_FRACTION_IN_WINDOW, PROCESSING_TIME_FRACTION_IN_WINDOW_PER_NODE) ); for (List> es : summingEnricherSetup) { AttributeSensor t = es.get(0); AttributeSensor total = es.get(1); enrichers().add(Enrichers.builder() .aggregating(t) .publishing(total) .fromMembers() .computingSum() .build()); } for (List> es : averagingEnricherSetup) { @SuppressWarnings("unchecked") AttributeSensor t = (AttributeSensor) es.get(0); @SuppressWarnings("unchecked") AttributeSensor average = (AttributeSensor) es.get(1); enrichers().add(Enrichers.builder() .aggregating(t) .publishing(average) .fromMembers() .computingAverage() .defaultValueForUnreportedSensors(0) .build()); } } // TODO this will probably be useful elsewhere ... but where to put it? // TODO add support for this in DependentConfiguration (see TODO there) /** Waits for the given target to report service up, then runs the given task * (often an invocation on that entity), with the given name. * If the target goes away, this task marks itself inessential * before failing so as not to cause a parent task to fail. */ static Task whenServiceUp(final Entity target, final TaskAdaptable task, String name) { return Tasks.builder().displayName(name).dynamic(true).body(new Callable() { @Override public T call() { try { while (true) { if (!Entities.isManaged(target)) { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed"); } if (Boolean.TRUE.equals(target.getAttribute(Attributes.SERVICE_UP))) { Tasks.resetBlockingDetails(); TaskTags.markInessential(task); DynamicTasks.queue(task); try { return task.asTask().getUnchecked(); } catch (Exception e) { if (Entities.isManaged(target)) { throw Exceptions.propagate(e); } else { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed", e); } } } else { Tasks.setBlockingDetails("Waiting on "+target+" to be ready"); } // TODO replace with subscription? Time.sleep(Duration.ONE_SECOND); } } finally { Tasks.resetBlockingDetails(); } } }).build(); } @Override public void deploy(String url, String targetName) { checkNotNull(url, "url"); checkNotNull(targetName, "targetName"); targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // set it up so future nodes get the right wars addToWarsByContext(this, url, targetName); log.debug("Deploying "+targetName+"->"+url+" across cluster "+this+"; WARs now "+getConfig(WARS_BY_CONTEXT)); Iterable targets = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName("Deploy "+targetName+" to cluster (size "+Iterables.size(targets)+")"); for (Entity target: targets) { tb.add(whenServiceUp(target, Effectors.invocation(target, DEPLOY, MutableMap.of("url", url, "targetName", targetName)), "Deploy "+targetName+" to "+target+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); // Update attribute // TODO support for atomic sensor update (should be part of standard tooling; NB there is some work towards this, according to @aledsage) Set deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS)); deployedWars.add(targetName); sensors().set(DEPLOYED_WARS, deployedWars); } @Override public void undeploy(String targetName) { checkNotNull(targetName, "targetName"); targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // set it up so future nodes get the right wars if (!removeFromWarsByContext(this, targetName)) { DynamicTasks.submit(Tasks.warning("Context "+targetName+" not known at "+this+"; attempting to undeploy regardless", null), this); } log.debug("Undeploying "+targetName+" across cluster "+this+"; WARs now "+getConfig(WARS_BY_CONTEXT)); Iterable targets = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName("Undeploy "+targetName+" across cluster (size "+Iterables.size(targets)+")"); for (Entity target: targets) { tb.add(whenServiceUp(target, Effectors.invocation(target, UNDEPLOY, MutableMap.of("targetName", targetName)), "Undeploy "+targetName+" at "+target+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); // Update attribute Set deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS)); deployedWars.remove( FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName) ); sensors().set(DEPLOYED_WARS, deployedWars); } static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // TODO a better way to do atomic updates, see comment above synchronized (entity) { Map newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); entity.config().set(WARS_BY_CONTEXT, newWarsMap); } } static boolean removeFromWarsByContext(Entity entity, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // TODO a better way to do atomic updates, see comment above synchronized (entity) { Map newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); String url = newWarsMap.remove(targetName); if (url==null) { return false; } entity.config().set(WARS_BY_CONTEXT, newWarsMap); return true; } } @Override public void redeployAll() { Map wars = MutableMap.copyOf(getConfig(WARS_BY_CONTEXT)); String redeployPrefix = "Redeploy all WARs (count "+wars.size()+")"; log.debug("Redeplying all WARs across cluster "+this+": "+getConfig(WARS_BY_CONTEXT)); Iterable targetEntities = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName(redeployPrefix+" across cluster (size "+Iterables.size(targetEntities)+")"); for (Entity targetEntity: targetEntities) { TaskBuilder redeployAllToTarget = Tasks.builder().displayName(redeployPrefix+" at "+targetEntity+" (after ready check)"); for (String warContextPath: wars.keySet()) { redeployAllToTarget.add(Effectors.invocation(targetEntity, DEPLOY, MutableMap.of("url", wars.get(warContextPath), "targetName", warContextPath))); } tb.add(whenServiceUp(targetEntity, redeployAllToTarget.build(), redeployPrefix+" at "+targetEntity+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2413 | https://github.com/apache/brooklyn-library/blob/89795c5d67d594259df9b4ea8bae766660e8b283/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterImpl.java/#L62-L261 | 2 | 222 | 2413 | major |
| 30 | {"response": "YES I found bad smells", "bad smells are": ["Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 719 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 30 | 719 | critical |
| 2491 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DiscoverAnnotatedBeans implements DynamicDeployer { public AppModule deploy(AppModule appModule) throws OpenEJBException { for (EjbModule ejbModule : appModule.getEjbModules()) { ejbModule.initAppModule(appModule); setModule(ejbModule); try { deploy(ejbModule); } finally { removeModule(); } } for (ClientModule clientModule : appModule.getClientModules()) { clientModule.initAppModule(appModule); setModule(clientModule); try { deploy(clientModule); } finally { removeModule(); } } for (ConnectorModule connectorModule : appModule.getConnectorModules()) { connectorModule.initAppModule(appModule); setModule(connectorModule); try { deploy(connectorModule); } finally { removeModule(); } } for (WebModule webModule : appModule.getWebModules()) { webModule.initAppModule(appModule); setModule(webModule); try { deploy(webModule); } finally { removeModule(); } } final AdditionalBeanDiscoverer discoverer = SystemInstance.get().getComponent(AdditionalBeanDiscoverer.class); if (discoverer != null) { appModule = discoverer.discover(appModule); } return appModule; } public ClientModule deploy(ClientModule clientModule) throws OpenEJBException { if (clientModule.getApplicationClient() == null){ clientModule.setApplicationClient(new ApplicationClient()); } // Lots of jars have main classes so this might not even be an app client. // We're not going to scrape it for @LocalClient or @RemoteClient annotations // unless they flag us specifically by adding a META-INF/application-client.xml // // ClientModules that already have a AnnotationFinder have been generated automatically // from an EjbModule, so we don't skip those ever. if (clientModule.getFinder() == null && clientModule.getAltDDs().containsKey("application-client.xml")) if (clientModule.getApplicationClient() != null && clientModule.getApplicationClient().isMetadataComplete()) return clientModule; IAnnotationFinder finder = clientModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(clientModule); } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForClientModule.url", clientModule.getJarLocation()); return clientModule; } catch (Exception e) { startupLogger.warning("startup.scrapeFailedForClientModule", e, clientModule.getJarLocation()); return clientModule; } } // This method is also called by the deploy(EjbModule) method to see if those // modules have any @LocalClient or @RemoteClient classes for (Annotated> clazz : finder.findMetaAnnotatedClasses(LocalClient.class)) { clientModule.getLocalClients().add(clazz.get().getName()); } for (Annotated> clazz : finder.findMetaAnnotatedClasses(RemoteClient.class)) { clientModule.getRemoteClients().add(clazz.get().getName()); } if (clientModule.getApplicationClient() == null){ if (clientModule.getRemoteClients().size() > 0 || clientModule.getLocalClients().size() > 0) { clientModule.setApplicationClient(new ApplicationClient()); } } return clientModule; } public ConnectorModule deploy(ConnectorModule connectorModule) throws OpenEJBException { org.apache.openejb.jee.Connector connector = connectorModule.getConnector(); if (connector == null) { connector = new org.apache.openejb.jee.Connector(); } // JCA 1.6 - 18.3.1 do not look at annotations if the provided connector // deployment descriptor is "meta-data complete". float specVersion = 0; try { specVersion = Float.parseFloat(connector.getVersion()); } catch (Exception e) { } if (specVersion < 1.6 || Boolean.TRUE.equals(connector.isMetadataComplete())) { return connectorModule; } IAnnotationFinder finder = connectorModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(connectorModule); connectorModule.setFinder(finder); } catch (Exception e) { // TODO: some sort of error return connectorModule; } } List> connectorClasses = finder.findAnnotatedClasses(Connector.class); // are we allowed to have more than one connector class? Not without a deployment descriptor if (connector.getResourceAdapter() == null || connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { if (connectorClasses.size() == 0) { // fail some validation here too } if (connectorClasses.size() > 1) { // too many connector classes, this is against the spec // something like connectorModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); } } Class connectorClass = null; if (connectorClasses.size() == 1) { connectorClass = connectorClasses.get(0); } if (connectorClasses.size() > 1) { for (Class cls : connectorClasses) { if (cls.getName().equals(connector.getResourceAdapter().getResourceAdapterClass())) { connectorClass = cls; break; } } } if (connectorClass != null) { if (connector.getResourceAdapter() == null) { connector.setResourceAdapter(new ResourceAdapter()); } if (connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { connector.getResourceAdapter().setResourceAdapterClass(connectorClass.getName()); } Connector connectorAnnotation = connectorClass.getAnnotation(Connector.class); connector.setDisplayNames(getTexts(connector.getDisplayNames(), connectorAnnotation.displayName())); connector.setDescriptions(getTexts(connector.getDescriptions(), connectorAnnotation.description())); connector.setEisType(getString(connector.getEisType(), connectorAnnotation.eisType())); connector.setVendorName(getString(connector.getVendorName(), connectorAnnotation.vendorName())); connector.setResourceAdapterVersion(getString(connector.getResourceAdapterVersion(), connectorAnnotation.version())); if (connector.getIcons().isEmpty()) { int smallIcons = connectorAnnotation.smallIcon().length; int largeIcons = connectorAnnotation.largeIcon().length; for (int i = 0; i < smallIcons && i < largeIcons; i++) { Icon icon = new Icon(); // locale can't be specified in the annotation and it is en by default // so on other systems it doesn't work because Icon return the default locale icon.setLang(Locale.getDefault().getLanguage()); if (i < smallIcons) { icon.setSmallIcon(connectorAnnotation.smallIcon()[i]); } if (i < largeIcons) { icon.setLargeIcon(connectorAnnotation.largeIcon()[i]); } connector.getIcons().add(icon); } } if (connector.getLicense() == null) { License license = new License(); connector.setLicense(license); license.setLicenseRequired(connectorAnnotation.licenseRequired()); } connector.getLicense().setDescriptions(getTexts(connector.getLicense().getDescriptions(), connectorAnnotation.licenseDescription())); SecurityPermission[] annotationSecurityPermissions = connectorAnnotation.securityPermissions(); List securityPermission = connector.getResourceAdapter().getSecurityPermission(); if (securityPermission == null || securityPermission.size() == 0) { for (SecurityPermission sp : annotationSecurityPermissions) { org.apache.openejb.jee.SecurityPermission permission = new org.apache.openejb.jee.SecurityPermission(); permission.setSecurityPermissionSpec(sp.permissionSpec()); permission.setDescriptions(stringsToTexts(sp.description())); securityPermission.add(permission); } } Class[] annotationRequiredWorkContexts = connectorAnnotation.requiredWorkContexts(); List requiredWorkContext = connector.getRequiredWorkContext(); if (requiredWorkContext.size() == 0) { for (Class cls : annotationRequiredWorkContexts) { requiredWorkContext.add(cls.getName()); } } OutboundResourceAdapter outboundResourceAdapter = connector.getResourceAdapter().getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); connector.getResourceAdapter().setOutboundResourceAdapter(outboundResourceAdapter); } List authenticationMechanisms = outboundResourceAdapter.getAuthenticationMechanism(); javax.resource.spi.AuthenticationMechanism[] authMechanisms = connectorAnnotation.authMechanisms(); if (authenticationMechanisms.size() == 0) { for (javax.resource.spi.AuthenticationMechanism am : authMechanisms) { AuthenticationMechanism authMechanism = new AuthenticationMechanism(); authMechanism.setAuthenticationMechanismType(am.authMechanism()); authMechanism.setCredentialInterface(am.credentialInterface().toString()); authMechanism.setDescriptions(stringsToTexts(am.description())); authenticationMechanisms.add(authMechanism); } } if (outboundResourceAdapter.getTransactionSupport() == null) { outboundResourceAdapter.setTransactionSupport(TransactionSupportType.fromValue(connectorAnnotation.transactionSupport().toString())); } if (outboundResourceAdapter.isReauthenticationSupport() == null) { outboundResourceAdapter.setReauthenticationSupport(connectorAnnotation.reauthenticationSupport()); } } else { // we couldn't process a connector class - probably a validation issue which we should warn about. } // process @ConnectionDescription(s) List> classes = finder.findAnnotatedClasses(ConnectionDefinitions.class); for (Class cls : classes) { ConnectionDefinitions connectionDefinitionsAnnotation = cls.getAnnotation(ConnectionDefinitions.class); ConnectionDefinition[] definitions = connectionDefinitionsAnnotation.value(); for (ConnectionDefinition definition : definitions) { processConnectionDescription(connector.getResourceAdapter(), definition, cls); } } classes = finder.findAnnotatedClasses(ConnectionDefinition.class); for (Class cls : classes) { ConnectionDefinition connectionDefinitionAnnotation = cls.getAnnotation(ConnectionDefinition.class); processConnectionDescription(connector.getResourceAdapter(), connectionDefinitionAnnotation, cls); } InboundResourceadapter inboundResourceAdapter = connector.getResourceAdapter().getInboundResourceAdapter(); if (inboundResourceAdapter == null) { inboundResourceAdapter = new InboundResourceadapter(); connector.getResourceAdapter().setInboundResourceAdapter(inboundResourceAdapter); } MessageAdapter messageAdapter = inboundResourceAdapter.getMessageAdapter(); if (messageAdapter == null) { messageAdapter = new MessageAdapter(); inboundResourceAdapter.setMessageAdapter(messageAdapter); } classes = finder.findAnnotatedClasses(Activation.class); for (Class cls : classes) { MessageListener messageListener = null; Activation activationAnnotation = cls.getAnnotation(Activation.class); List messageListeners = messageAdapter.getMessageListener(); for (MessageListener ml : messageListeners) { if (cls.getName().equals(ml.getActivationSpec().getActivationSpecClass())) { messageListener = ml; break; } } if (messageListener == null) { Class[] listeners = activationAnnotation.messageListeners(); for (Class listener : listeners) { messageAdapter.addMessageListener(new MessageListener(listener.getName(), cls.getName())); } } } classes = finder.findAnnotatedClasses(AdministeredObject.class); List adminObjects = connector.getResourceAdapter().getAdminObject(); for (Class cls : classes) { AdministeredObject administeredObjectAnnotation = cls.getAnnotation(AdministeredObject.class); Class[] adminObjectInterfaces = administeredObjectAnnotation.adminObjectInterfaces(); AdminObject adminObject = null; for (AdminObject admObj : adminObjects) { if (admObj.getAdminObjectClass().equals(cls.getName())) { adminObject = admObj; } } if (adminObject == null) { for (Class iface : adminObjectInterfaces) { AdminObject newAdminObject = new AdminObject(); newAdminObject.setAdminObjectClass(cls.getName()); newAdminObject.setAdminObjectInterface(iface.getName()); adminObjects.add(newAdminObject); } } } // need to make a list of classes to process for config properties // resource adapter String raCls = connector.getResourceAdapter().getResourceAdapterClass(); process(connectorModule.getClassLoader(), raCls, connector.getResourceAdapter()); // managedconnectionfactory if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getOutboundResourceAdapter() != null) { List connectionDefinitions = connector.getResourceAdapter().getOutboundResourceAdapter().getConnectionDefinition(); for (org.apache.openejb.jee.ConnectionDefinition connectionDefinition : connectionDefinitions) { process(connectorModule.getClassLoader(), connectionDefinition.getManagedConnectionFactoryClass(), connectionDefinition); } } // administeredobject if (connector.getResourceAdapter() != null) { List raAdminObjects = connector.getResourceAdapter().getAdminObject(); for (AdminObject raAdminObject : raAdminObjects) { process(connectorModule.getClassLoader(), raAdminObject.getAdminObjectClass(), raAdminObject); } } // activationspec if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter() != null) { List messageListeners = connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter().getMessageListener(); for (MessageListener messageListener : messageListeners) { ActivationSpec activationSpec = messageListener.getActivationSpec(); process(connectorModule.getClassLoader(), activationSpec.getActivationSpecClass(), activationSpec); } } return connectorModule; } void process(ClassLoader cl, String cls, Object object) { List configProperties = null; try { // grab a list of ConfigProperty objects configProperties = (List) object.getClass().getDeclaredMethod("getConfigProperty").invoke(object); } catch (Exception e) { } if (configProperties == null) { // can't get config properties return; } ClassLoader classLoader = cl; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final List allowedTypes = Arrays.asList(new String[] { Boolean.class.getName(), String.class.getName(), Integer.class.getName(), Double.class.getName(), Byte.class.getName(), Short.class.getName(), Long.class.getName(), Float.class.getName(), Character.class.getName()}); try { Class clazz = classLoader.loadClass(realClassName(cls)); Object o = clazz.newInstance(); // add any introspected properties BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); Class type = propertyDescriptor.getPropertyType(); if (type == null) { continue; } if (type.isPrimitive()) { type = getWrapper(type.getName()); } if (! allowedTypes.contains(type.getName())) { continue; } if (! containsConfigProperty(configProperties, name)) { if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); Object value = null; try { value = propertyDescriptor.getReadMethod().invoke(o); } catch (Exception e) { } javax.resource.spi.ConfigProperty annotation = propertyDescriptor.getWriteMethod().getAnnotation(javax.resource.spi.ConfigProperty.class); if (annotation == null) { try { // if there's no annotation on the setter, we'll try and scrape one off the field itself (assuming the same name) annotation = clazz.getDeclaredField(name).getAnnotation(javax.resource.spi.ConfigProperty.class); } catch (Exception ignored) { // no-op : getDeclaredField() throws exceptions and does not return null } } configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(getConfigPropertyType(annotation, type)); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null && annotation.defaultValue().length() > 0) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); configProperty.setDescriptions(stringsToTexts(annotation.description())); } } } } // add any annotated fields we haven't already picked up Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { javax.resource.spi.ConfigProperty annotation = field.getAnnotation(javax.resource.spi.ConfigProperty.class); String name = field.getName(); Object value = null; try { value = field.get(o); } catch (Exception e) { } if (! containsConfigProperty(configProperties, name)) { String type = getConfigPropertyType(annotation, field.getType()); if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(type); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); } } } } } catch (Exception e) { e.printStackTrace(); } } private String getConfigPropertyType(javax.resource.spi.ConfigProperty annotation, Class type) { Class t = (annotation == null) ? null : annotation.type(); if (t == null && type != null) { return type.getName(); } else if (t == null) { return null; } if (t.equals(Object.class)) { t = type; } if (t == null) { // t == null && type == null return null; } if (t.isPrimitive()) { t = getWrapper(t.getName()); } return t.getName(); } private boolean containsConfigProperty(List configProperties, String name) { for (ConfigProperty configProperty : configProperties) { if (configProperty.getConfigPropertyName().equals(name)) { return true; } } return false; } private Class getWrapper(String primitiveType) { final Map> builtInMap = new HashMap>();{ builtInMap.put("int", Integer.class); builtInMap.put("long", Long.class); builtInMap.put("double", Double.class); builtInMap.put("float", Float.class); builtInMap.put("boolean", Boolean.class); builtInMap.put("char", Character.class); builtInMap.put("byte", Byte.class); builtInMap.put("void", Void.class); builtInMap.put("short", Short.class); } return builtInMap.get(primitiveType); } private void processConnectionDescription(ResourceAdapter resourceAdapter, ConnectionDefinition connectionDefinitionAnnotation, Class cls) { // try and find the managed connection factory OutboundResourceAdapter outboundResourceAdapter = resourceAdapter.getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); resourceAdapter.setOutboundResourceAdapter(outboundResourceAdapter); } List connectionDefinition = outboundResourceAdapter.getConnectionDefinition(); org.apache.openejb.jee.ConnectionDefinition definition = null; for (org.apache.openejb.jee.ConnectionDefinition cd : connectionDefinition) { if (cd.getManagedConnectionFactoryClass().equals(cls.getName())) { definition = cd; break; } } if (definition == null) { definition = new org.apache.openejb.jee.ConnectionDefinition(); outboundResourceAdapter.getConnectionDefinition().add(definition); } if (definition.getManagedConnectionFactoryClass() == null) { definition.setManagedConnectionFactoryClass(cls.getName()); } if (definition.getConnectionInterface() == null) { definition.setConnectionInterface(connectionDefinitionAnnotation.connection().getName()); } if (definition.getConnectionImplClass() == null) { definition.setConnectionImplClass(connectionDefinitionAnnotation.connectionImpl().getName()); } if (definition.getConnectionFactoryInterface() == null) { definition.setConnectionFactoryInterface(connectionDefinitionAnnotation.connectionFactory().getName()); } if (definition.getConnectionFactoryImplClass() == null) { definition.setConnectionFactoryImplClass(connectionDefinitionAnnotation.connectionFactoryImpl().getName()); } } private Text[] stringsToTexts(String[] strings) { if (strings == null) { return null; } Text[] result = new Text[strings.length]; for (int i = 0; i < result.length; i++) { result[i] = new Text(); result[i].setValue(strings[i]); } return result; } private String getString(String descriptorString, String annotationString) { if (descriptorString != null && descriptorString.length() > 0) { return descriptorString; } if (annotationString != null && annotationString.length() > 0) { return annotationString; } return null; } private Text[] getTexts(Text[] originalTexts, String[] newStrings) { if (newStrings != null && newStrings.length > 0 && (originalTexts == null || originalTexts.length == 0)) { Text[] texts = new Text[newStrings.length]; for (int i = 0; i < newStrings.length; i++) { texts[i] = new Text(null, newStrings[i]); } return texts; } else { return originalTexts; } } public WebModule deploy(WebModule webModule) throws OpenEJBException { WebApp webApp = webModule.getWebApp(); if (webApp != null && (webApp.isMetadataComplete())) return webModule; try { if (webModule.getFinder() == null) { webModule.setFinder(FinderFactory.createFinder(webModule)); } } catch (Exception e) { startupLogger.warning("Unable to scrape for @WebService or @WebServiceProvider annotations. AnnotationFinder failed.", e); return webModule; } if (webApp == null) { webApp = new WebApp(); webModule.setWebApp(webApp); } List existingServlets = new ArrayList(); for (Servlet servlet : webApp.getServlet()) { if (servlet.getServletClass() != null) { existingServlets.add(servlet.getServletClass()); } } IAnnotationFinder finder = webModule.getFinder(); List classes = new ArrayList(); classes.addAll(finder.findAnnotatedClasses(WebService.class)); classes.addAll(finder.findAnnotatedClasses(WebServiceProvider.class)); for (Class webServiceClass : classes) { // If this class is also annotated @Stateless or @Singleton, we should skip it if (webServiceClass.isAnnotationPresent(Singleton.class) || webServiceClass.isAnnotationPresent(Stateless.class)) { webModule.getEjbWebServices().add(webServiceClass.getName()); continue; } int modifiers = webServiceClass.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || isAbstract(modifiers)) { continue; } if (existingServlets.contains(webServiceClass.getName())) continue; // create webApp and webservices objects if they don't exist already // add new element Servlet servlet = new Servlet(); servlet.setServletName(webServiceClass.getName()); servlet.setServletClass(webServiceClass.getName()); webApp.getServlet().add(servlet); } /* * REST */ // get by annotations webModule.getRestClasses().addAll(findRestClasses(webModule, finder)); addJaxRsProviders(finder, webModule.getJaxrsProviders(), Provider.class); // Applications with a default constructor // findSubclasses will not work by default to gain a lot of time // look FinderFactory for the flag to activate it or // use @ApplicationPath("/") List> applications = finder.findSubclasses(Application.class); for (Class app : applications) { addRestApplicationIfPossible(webModule, app); } // look for ApplicationPath, it will often return the same than the previous one // but without finder.link() invocation it still works // so it can save a lot of startup time List>> applicationsByAnnotation = finder.findMetaAnnotatedClasses(ApplicationPath.class); for (Annotated> annotatedApp : applicationsByAnnotation) { final Class app = annotatedApp.get(); if (!Application.class.isAssignableFrom(app)) { logger.error("class '" + app.getName() + "' is annotated with @ApplicationPath but doesn't implement " + Application.class.getName()); continue; } addRestApplicationIfPossible(webModule, (Class) app); } /* * JSF */ final ClassLoader classLoader = webModule.getClassLoader(); for (String jsfClass : JSF_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(jsfClass); } catch (ClassNotFoundException e) { continue; } final List>> found = finder.findMetaAnnotatedClasses(clazz); final Set convertedClasses = new HashSet(found.size()); for (Annotated> annotated : found) { convertedClasses.add(annotated.get().getName()); } webModule.getJsfAnnotatedClasses().put(jsfClass, convertedClasses); } /* * Servlet, Filter, Listener */ Map urlByClasses = null; for (String apiClassName : WEB_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(apiClassName); } catch (ClassNotFoundException e) { continue; } if (urlByClasses == null) { // try to reuse scanning info, maybe some better indexing can be a nice idea if (finder instanceof FinderFactory.ModuleLimitedFinder) { final IAnnotationFinder limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (limitedFinder instanceof AnnotationFinder) { final Archive archive = ((AnnotationFinder) limitedFinder).getArchive(); if (archive instanceof WebappAggregatedArchive) { final Map> index = ((WebappAggregatedArchive) archive).getClassesMap(); urlByClasses = new HashMap(); for (Map.Entry> entry : index.entrySet()) { final String url = entry.getKey().toExternalForm(); for (String current : entry.getValue()) { urlByClasses.put(current, url); } } } } } } final List>> found = finder.findMetaAnnotatedClasses(clazz); addWebAnnotatedClassInfo(urlByClasses, webModule.getWebAnnotatedClasses(), found); } if (urlByClasses != null) { urlByClasses.clear(); } return webModule; } private void addJaxRsProviders(final IAnnotationFinder finder, final Collection set, final Class annotation) { for (Annotated> provider : finder.findMetaAnnotatedClasses(annotation)) { set.add(provider.get().getName()); } } private static void addRestApplicationIfPossible(final WebModule webModule, final Class app) { if (app.getConstructors().length == 0) { webModule.getRestApplications().add(app.getName()); } else { for (Constructor ctr : app.getConstructors()) { if (ctr.getParameterTypes().length == 0) { webModule.getRestApplications().add(app.getName()); break; } } } } public EjbModule deploy(EjbModule ejbModule) throws OpenEJBException { if (ejbModule.getEjbJar() != null && ejbModule.getEjbJar().isMetadataComplete()) return ejbModule; try { if (ejbModule.getFinder() == null) { ejbModule.setFinder(FinderFactory.createFinder(ejbModule)); } } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForModule", ejbModule.getJarLocation()); return ejbModule; } catch (Exception e) { startupLogger.warning("Unable to scrape for @Stateful, @Stateless, @Singleton or @MessageDriven annotations. AnnotationFinder failed.", e); return ejbModule; } IAnnotationFinder finder = ejbModule.getFinder(); final List managedClasses; { final Beans beans = ejbModule.getBeans(); if (beans != null) { managedClasses = beans.getManagedClasses(); final List classNames = getBeanClasses(finder); for (String rawClassName : classNames) { final String className = realClassName(rawClassName); try { final ClassLoader loader = ejbModule.getClassLoader(); final Class clazz = loader.loadClass(className); // The following can NOT be beans in CDI // 1. Non-static inner classes if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) continue; // // // 2. Abstract classes (unless they are an @Decorator) // if (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isAnnotationPresent(javax.decorator.Decorator.class)) continue; // // 3. Implementations of Extension if (Extension.class.isAssignableFrom(clazz)) continue; managedClasses.add(className); } catch (ClassNotFoundException e) { // todo log debug warning } catch (java.lang.NoClassDefFoundError e) { // no-op } } // passing jar location to be able to manage maven classes/test-classes which have the same moduleId String id = ejbModule.getModuleId(); if (ejbModule.getJarLocation() != null && ejbModule.getJarLocation().contains(ejbModule.getModuleId() + "/target/test-classes".replace("/", File.separator))) { // with maven if both src/main/java and src/test/java are deployed // moduleId.Comp exists twice so it fails // here we simply modify the test comp bean name to avoid it id += "_test"; } final String name = BeanContext.Comp.openejbCompName(id); final org.apache.openejb.jee.ManagedBean managedBean = new CompManagedBean(name, BeanContext.Comp.class); managedBean.setTransactionType(TransactionType.BEAN); ejbModule.getEjbJar().addEnterpriseBean(managedBean); } else { managedClasses = new ArrayList(); } } final Set> specializingClasses = new HashSet>(); // Fill in default sessionType for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (!(bean instanceof SessionBean)) continue; SessionBean sessionBean = (SessionBean) bean; if (sessionBean.getSessionType() != null) continue; try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); sessionBean.setSessionType(getSessionType(clazz)); } catch (Throwable handledInValidation) { // no-op } } // Fill in default ejbName for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (bean.getEjbClass() == null) continue; if (bean.getEjbName() == null || bean.getEjbName().startsWith("@NULL@")) { ejbModule.getEjbJar().removeEnterpriseBean(bean.getEjbName()); try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); final String ejbName = getEjbName(bean, clazz); bean.setEjbName(ejbName); } catch (Throwable handledInValidation) { } ejbModule.getEjbJar().addEnterpriseBean(bean); } } /* 19.2: ejb-name: Default is the unqualified name of the bean class */ EjbJar ejbJar = ejbModule.getEjbJar(); for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Singleton.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Singleton singleton = beanClass.getAnnotation(Singleton.class); String ejbName = getEjbName(singleton, beanClass.get()); if (!isValidEjbAnnotationUsage(Singleton.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new SingletonBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.SINGLETON); if (singleton.mappedName() != null) { sessionBean.setMappedName(singleton.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateless.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateless stateless = beanClass.getAnnotation(Stateless.class); String ejbName = getEjbName(stateless, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateless.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatelessBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.STATELESS); if (stateless.mappedName() != null) { sessionBean.setMappedName(stateless.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } // The Specialization code is good, but it possibly needs to be moved to after the full processing of the bean // the plus is that it would get the required interfaces. The minus is that it would get all the other items // Possibly study alternatives. Alternatives might have different meta data completely while it seems Specializing beans inherit all meta-data // Anyway.. the qualifiers aren't getting inherited, so we need to fix that for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateful.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateful stateful = beanClass.getAnnotation(Stateful.class); String ejbName = getEjbName(stateful, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateful.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatefulBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; // TODO: We might be stepping on an xml override here sessionBean.setSessionType(SessionType.STATEFUL); if (stateful.mappedName() != null) { sessionBean.setMappedName(stateful.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(ManagedBean.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } ManagedBean managed = beanClass.getAnnotation(ManagedBean.class); String ejbName = getEjbName(managed, beanClass.get()); // TODO: this is actually against the spec, but the requirement is rather silly // (allowing @Stateful and @ManagedBean on the same class) // If the TCK doesn't complain we should discourage it if (!isValidEjbAnnotationUsage(ManagedBean.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new org.apache.openejb.jee.ManagedBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.MANAGED); final TransactionType transactionType = sessionBean.getTransactionType(); if (transactionType == null) sessionBean.setTransactionType(TransactionType.BEAN); } } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(MessageDriven.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } MessageDriven mdb = beanClass.getAnnotation(MessageDriven.class); String ejbName = getEjbName(mdb, beanClass.get()); if (!isValidEjbAnnotationUsage(MessageDriven.class, beanClass, ejbName, ejbModule)) continue; MessageDrivenBean messageBean = (MessageDrivenBean) ejbJar.getEnterpriseBean(ejbName); if (messageBean == null) { messageBean = new MessageDrivenBean(ejbName); ejbJar.addEnterpriseBean(messageBean); } if (messageBean.getEjbClass() == null) { messageBean.setEjbClass(beanClass.get()); } LegacyProcessor.process(beanClass.get(), messageBean); } for (Class specializingClass : sortClassesParentFirst(new ArrayList>(specializingClasses))) { final Class parent = specializingClass.getSuperclass(); if (parent == null || parent.equals(Object.class)) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsNothing", specializingClass.getName()); } boolean found = false; for (EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) { final String ejbClass = enterpriseBean.getEjbClass(); if (ejbClass != null && ejbClass.equals(parent.getName())) { managedClasses.remove(ejbClass); enterpriseBean.setEjbClass(specializingClass.getName()); found = true; } } if (!found) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsSimpleBean", specializingClass.getName()); } } AssemblyDescriptor assemblyDescriptor = ejbModule.getEjbJar().getAssemblyDescriptor(); if (assemblyDescriptor == null) { assemblyDescriptor = new AssemblyDescriptor(); ejbModule.getEjbJar().setAssemblyDescriptor(assemblyDescriptor); } startupLogger.debug("Searching for annotated application exceptions (see OPENEJB-980)"); List> appExceptions = finder.findAnnotatedClasses(ApplicationException.class); for (Class exceptionClass : appExceptions) { startupLogger.debug("...handling " + exceptionClass); ApplicationException annotation = exceptionClass.getAnnotation(ApplicationException.class); if (assemblyDescriptor.getApplicationException(exceptionClass) == null) { startupLogger.debug("...adding " + exceptionClass + " with rollback=" + annotation.rollback()); assemblyDescriptor.addApplicationException(exceptionClass, annotation.rollback(), annotation.inherited()); } else { mergeApplicationExceptionAnnotation(assemblyDescriptor, exceptionClass, annotation); } } // ejb can be rest bean and only then in standalone so scan providers here too // adding them to app since they should be in the app classloader if (ejbModule.getAppModule() != null) { addJaxRsProviders(finder, ejbModule.getAppModule().getJaxRsProviders(), Provider.class); } if (ejbModule.getAppModule() != null) { for (PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) { for (org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) { if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses()) && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) { final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE); // no need of meta currently since JPA providers doesn't support it final List> classes = new ArrayList>(); classes.addAll(finder.findAnnotatedClasses(Entity.class)); classes.addAll(finder.findAnnotatedClasses(Embeddable.class)); classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class)); final List existingClasses = pu.getClazz(); for (Class clazz : classes) { final String name = clazz.getName(); if ((packageName == null || name.startsWith(packageName)) && !existingClasses.contains(name)) { pu.getClazz().add(name); } } pu.setScanned(true); } } } } return ejbModule; } private SessionType getSessionType(Class clazz) { if (clazz.isAnnotationPresent(Stateful.class)) return SessionType.STATEFUL; if (clazz.isAnnotationPresent(Stateless.class)) return SessionType.STATELESS; if (clazz.isAnnotationPresent(Singleton.class)) return SessionType.SINGLETON; if (clazz.isAnnotationPresent(ManagedBean.class)) return SessionType.MANAGED; return null; } private String getEjbName(EnterpriseBean bean, Class clazz) { if (bean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) bean; switch (sessionBean.getSessionType()) { case STATEFUL: { final Stateful annotation = clazz.getAnnotation(Stateful.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case STATELESS: { final Stateless annotation = clazz.getAnnotation(Stateless.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case SINGLETON: { final Singleton annotation = clazz.getAnnotation(Singleton.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } } } if (bean instanceof MessageDrivenBean) { final MessageDriven annotation = clazz.getAnnotation(MessageDriven.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } return clazz.getSimpleName(); } private static boolean specified(final String name) { return name != null && name.length() != 0; } private List getBeanClasses(IAnnotationFinder finder) { // What we're hoping in this method is to get lucky and find // that our 'finder' instances is an AnnotationFinder that is // holding an AggregatedArchive so we can get the classes that // that pertain to each URL for CDI purposes. // // If not we call finder.getAnnotatedClassNames() which may return // more classes than actually apply to CDI. This can "pollute" // the CDI class space and break injection points if (!(finder instanceof FinderFactory.ModuleLimitedFinder)) return finder.getAnnotatedClassNames(); final IAnnotationFinder delegate = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (!(delegate instanceof AnnotationFinder)) return finder.getAnnotatedClassNames(); final AnnotationFinder annotationFinder = (AnnotationFinder) delegate; final Archive archive = annotationFinder.getArchive(); if (!(archive instanceof WebappAggregatedArchive)) return finder.getAnnotatedClassNames(); final List classes = new ArrayList(); final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive; final Map> map = aggregatedArchive.getClassesMap(); for (Map.Entry> entry : map.entrySet()) { if (hasBeansXml(entry.getKey())) classes.addAll(entry.getValue()); } return classes; } public static boolean hasBeansXml(URL url) { if (url.getPath().endsWith("WEB-INF/classes/")) return true; if (url.getPath().endsWith("!/META-INF/beans.xml")) return true; try { final URLClassLoader loader = new URLClassLoader(new URL[]{ url } , new EmptyResourcesClassLoader()); String[] paths = { "META-INF/beans.xml", "WEB-INF/beans.xml", "/WEB-INF/beans.xml", "/META-INF/beans.xml", }; for (String path : paths) { if (loader.findResource(path) != null) return true; } } catch (Exception e) { } return false; } private String getEjbName(MessageDriven mdb, Class beanClass) { return (mdb.name().isEmpty() ? beanClass.getSimpleName() : mdb.name()); } private String getEjbName(Stateful stateful, Class beanClass) { return (stateful.name().isEmpty() ? beanClass.getSimpleName() : stateful.name()); } private String getEjbName(Stateless stateless, Class beanClass) { return (stateless.name().isEmpty() ? beanClass.getSimpleName() : stateless.name()); } private String getEjbName(Singleton singleton, Class beanClass) { return (singleton.name().isEmpty() ? beanClass.getSimpleName() : singleton.name()); } private String getEjbName(ManagedBean managed, Class beanClass) { return (managed.value().isEmpty() ? beanClass.getSimpleName() : managed.value()); } private boolean isValidEjbAnnotationUsage(Class annotationClass, Annotated> beanClass, String ejbName, EjbModule ejbModule) { List> annotations = new ArrayList(asList(Singleton.class, Stateless.class, Stateful.class, MessageDriven.class)); annotations.remove(annotationClass); boolean b = true; for (Class secondAnnotation : annotations) { Annotation annotation = beanClass.getAnnotation(secondAnnotation); if (annotation == null) continue; String secondEjbName = null; if (annotation instanceof Stateful) { secondEjbName = getEjbName((Stateful) annotation, beanClass.get()); } else if (annotation instanceof Stateless) { secondEjbName = getEjbName((Stateless) annotation, beanClass.get()); } else if (annotation instanceof Singleton) { secondEjbName = getEjbName((Singleton) annotation, beanClass.get()); } else if (annotation instanceof MessageDriven) { secondEjbName = getEjbName((MessageDriven) annotation, beanClass.get()); } if (ejbName.equals(secondEjbName)) { ejbModule.getValidation().fail(ejbName, "multiplyAnnotatedAsBean", annotationClass.getSimpleName(), secondAnnotation.getSimpleName(), ejbName, beanClass.get().getName()); } } // not a dynamic proxy implemented bean if (beanClass.getAnnotation(PersistenceContext.class) == null && beanClass.getAnnotation(Proxy.class) == null && beanClass.get().isInterface()) { ejbModule.getValidation().fail(ejbName, "interfaceAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } if (!beanClass.get().isInterface() && isAbstract(beanClass.get().getModifiers())) { ejbModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } return b; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 14620 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/config/AnnotationDeployer.java/#L411-L1700 | 1 | 2491 | 14620 | major |
| 2671 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15212 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2671 | 15212 | minor |
| 51 | {"answer": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ForeachCommand extends Command { public static String[] foreachArgs = null; public ForeachCommand() { addCommand("foreach", "", "build up a list of elements to operate on "); addCommand("do", "", "repeat a command for each element in the list"); } public void run(String command, final String[] args, final Context context, final PrintStream out) throws DDRInteractiveCommandException { if (command.equals("!do")) { boolean echo = false; boolean quiet = false; String token = null; int commandIndex = 0; while (commandIndex < args.length) { if (args[commandIndex].equals("help")) { out.println("The !do command is used to repeat a command on the elements gathered by the !foreach command."); out.println("Syntax: !do [echo] [quiet] [token=] [args]"); out.println(); out.println("\techo\t\tOutput each command before it is run."); out.println("\tquiet\t\tSuppress delimiters between command outputs."); out.println("\ttoken=\tSpecify a substitution token. Occurrencs of this string in the args will be replaced by the current element."); return; } else if (args[commandIndex].equals("echo")) { echo = true; commandIndex += 1; } else if (args[commandIndex].equals("quiet")) { quiet = true; commandIndex += 1; } else if (args[commandIndex].startsWith("token=")) { token = args[commandIndex].substring("token=".length()); commandIndex += 1; } else { break; } } if (commandIndex >= args.length) { out.println("The do command requires another command to repeat."); return; } if ((null == foreachArgs) || (0 == foreachArgs.length)) { out.println("Element list is empty. Use the foreach command to populate it."); return; } for (int i = 0; i < foreachArgs.length; i++) { if (!quiet && (i > 0)) { out.println("========================================"); } try { String[] newArgs; if (null == token) { newArgs = substituteArgs(args, commandIndex, i); } else { newArgs = substituteArgs(args, commandIndex, i, token); } if (echo) { System.out.println("> " + args[commandIndex] + " " + Arrays.toString(newArgs)); } CommandParser commandParser = new CommandParser(args[commandIndex], newArgs); context.execute(commandParser, out); } catch (ParseException e) { e.printStackTrace(out); } catch (Throwable th) { out.println("Exception while executing " + args[commandIndex] + " " + foreachArgs[i]); th.printStackTrace(out); } } } else if(command.equals("!foreach")) { if (args.length > 0) { out.println("The !foreach command takes no arguments, but will read lines from the console until it encounters a blank line."); out.println("These lines can then be used as arguments to commands specified using !do."); return; } ArrayList lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (0 == line.length()) { break; } else { lines.add(line); } } // split by , String[] newArgs = new String[lines.size()]; lines.toArray(newArgs); foreachArgs = newArgs; } } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex) { /* Concatenate: * */ String[] newArgs = new String[args.length - commandIndex]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); newArgs[newArgs.length - 1] = foreachArgs[foreachIndex]; return newArgs; } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex, String token) { /* Concatenate: * * Replacing any occurence of token with */ String[] newArgs = new String[args.length - commandIndex - 1]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); for (int i = 0; i < newArgs.length; i++) { newArgs[i] = newArgs[i].replace(token, foreachArgs[foreachIndex]); } return newArgs; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 872 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/tools/ddrinteractive/commands/ForeachCommand.java/#L37-L165 | 1 | 51 | 872 | minor |
| 3424 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AppService implements ApplicationService { private static final Logger logger = LoggerFactory.getLogger(ApplicationService.class); /** * Create an register an application service using the default alias {@link ApplicationService#ALIAS}. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @return Application service instance. */ public static ApplicationService createAndRegister(TopologyProvider provider, DirectSubmitter submitter) { AppService service = new AppService(provider, submitter, ALIAS); submitter.getServices().addService(ApplicationService.class, service); return service; } private final Map> applications = Collections.synchronizedMap(new HashMap<>()); private final TopologyProvider provider; private final DirectSubmitter submitter; /** * Create an {@code ApplicationService} instance. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @param alias Alias used to register the control MBean. */ public AppService(TopologyProvider provider, DirectSubmitter submitter, String alias) { this.provider = provider; this.submitter = submitter; ControlService cs = submitter.getServices().getService(ControlService.class); if (cs != null) cs.registerControl(ApplicationServiceMXBean.TYPE, ALIAS+System.currentTimeMillis(), alias, ApplicationServiceMXBean.class, new AppServiceControl(this)); } @Override public void registerTopology(String applicationName, BiConsumer builder) { if (applicationName == null || applicationName.isEmpty()) { throw new IllegalArgumentException(); } logger.trace("Register application name: {}", applicationName); applications.put(applicationName, builder); } /** * Create a new class loader for the jar and register any * topology application that is registered as a service provider. */ @Override public void registerJar(String jarURL, String jsonConfig) throws Exception { logger.trace("Register jar: {}", jarURL); // If it's a http URL download it otherwise use directly. URL url = new URL(jarURL); String protocol = url.getProtocol(); if ("http".equals(protocol) || "https".equals(protocol)) { url = downloadJar(url); } URLClassLoader loader = new URLClassLoader(new URL[] {url}); for (TopologyBuilder topoBuilder : ServiceLoader.load(TopologyBuilder.class, loader)) { registerTopology(topoBuilder.getName(), topoBuilder.getBuilder()); } } /** * Download an HTTP URL to a local file. * @param url URL to download from. * @return URL of the local file. */ private URL downloadJar(URL url) throws Exception { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Error response code for URL: {} : response code={}", url.toExternalForm(), responseCode); throw new IOException(); } String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); if (disposition != null) { // extracts file name from header field int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name from URL path String path = url.getPath(); if (!path.isEmpty()) { int lastSlash = path.lastIndexOf("/"); if (lastSlash == -1) fileName = path; else fileName = path.substring(lastSlash+1); } } // TODO - allow persistence across reboots // For now just store in a temp directory Path dir = Files.createTempDirectory("edgentjars"); File file; if (fileName.isEmpty()) file = File.createTempFile("edgent", "jar", dir.toFile()); else file = new File(dir.toFile(), fileName); InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); logger.trace("Register jar downloaded as: {}", file); return file.toURI().toURL(); } @Override public Set getApplicationNames() { synchronized (applications) { return new HashSet<>(applications.keySet()); } } BiConsumer getBuilder(String applicationName) { return applications.get(applicationName); } TopologyProvider getProvider() { return provider; } DirectSubmitter getSubmitter() { return submitter; } } |
blob | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | blob | 0 | 6745 | https://github.com/apache/incubator-edgent/blob/2e44089358175964650fed5e2bf4ad071b05b7d6/runtime/appservice/src/main/java/org/apache/edgent/runtime/appservice/AppService.java/#L62-L217 | 2 | 3424 | 6745 | minor |
| 1468 | YES I found bad smells the bad smells are: 1. Long method 2. Complex method 3. Data class 4. Primitive obsession 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
blob | Long method 2 Complex method 3 Data class 4 Primitive obsession 5 Feature envy | t | f | f | . Long method 2. Complex method 3. Data class 4. Primitive obsession 5. Feature envy | blob | 0 | 11044 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 1468 | 11044 | major |
| 857 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7892 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L20095-L20123 | 1 | 857 | 7892 | minor | ||
| 1583 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | f | f | f | long method | 0 | 11365 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 1583 | 11365 | minor | ||
| 5190 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14510 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5190 | 14510 | minor | ||
| 1412 | {"response": "YES I found bad smells", "the bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | blob | t | t | f | blob | data class | 0 | 10903 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 1412 | 10903 | major |
| 4023 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10632 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 2 | 4023 | 10632 | critical |
| 324 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup_1() { return cGroup_1; } //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0() { return cGroup_1_0; } //=> ({BinaryLogicalExpression.lhs=current} public Group getGroup_1_0_0() { return cGroup_1_0_0; } YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 3343 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 324 | 3343 | major |
| 2592 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
data class | long method | t | t | f | long method | data class | 0 | 15000 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 1 | 2592 | 15000 | major |
| 5640 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 10919 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5640 | 10919 | major |
| 594 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Primitive obsession 5. Lack of encapsulation 6. Lack of exception handling 7. Lack of use of interfaces or abstract classes 8. Use of mulitple return types 9. Inconsistent variable naming 10. Lack of readability 11. Complicated logic 12. Large class size 13. Use of nested classes/inner classes 14. Lack of modularity 15. Mixing of responsibilities 16. Lack of proper abstraction 17. Poor error handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class DirectExecutorService implements ExecutorService { static final DirectExecutorService INSTANCE = new DirectExecutorService(); private boolean isShutdown = false; @Override public void shutdown() { isShutdown = true; } @Override @Nonnull public List shutdownNow() { isShutdown = true; return Collections.emptyList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isShutdown; } @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) { return isShutdown; } @Override @Nonnull public Future submit(@Nonnull Callable task) { try { T result = task.call(); return new CompletedFuture<>(result, null); } catch (Exception e) { return new CompletedFuture<>(null, e); } } @Override @Nonnull public Future submit(@Nonnull Runnable task, T result) { task.run(); return new CompletedFuture<>(result, null); } @Override @Nonnull public Future submit(@Nonnull Runnable task) { task.run(); return new CompletedFuture<>(null, null); } @Override @Nonnull public List> invokeAll(@Nonnull Collection> tasks) { ArrayList> result = new ArrayList<>(); for (Callable task : tasks) { try { result.add(new CompletedFuture<>(task.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } return result; } @Override @Nonnull public List> invokeAll( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); Iterator> iterator = tasks.iterator(); ArrayList> result = new ArrayList<>(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { result.add(new CompletedFuture<>(callable.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } while (iterator.hasNext()) { iterator.next(); result.add(new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean isDone() { return false; } @Override public T get() { throw new CancellationException("Task has been cancelled."); } @Override public T get(long timeout, @Nonnull TimeUnit unit) { throw new CancellationException("Task has been cancelled."); } }); } return result; } @Override @Nonnull public T invokeAny(@Nonnull Collection> tasks) throws ExecutionException { Exception exception = null; for (Callable task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); } @Override public T invokeAny( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis(timeout); Exception exception = null; Iterator> iterator = tasks.iterator(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { return callable.call(); } catch (Exception e) { // ignore exception and try next exception = e; } } if (iterator.hasNext()) { throw new TimeoutException("Could not finish execution of tasks within time."); } else { throw new ExecutionException("No tasks finished successfully.", exception); } } @Override public void execute(@Nonnull Runnable command) { command.run(); } static class CompletedFuture implements Future { private final V value; private final Exception exception; CompletedFuture(V value, Exception exception) { this.value = value; this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public V get() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } else { return value; } } @Override public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException { return get(); } } } |
blob | Long method2 Feature envy3 Code duplication4 Primitive obsession 5 Lack of encapsulation 6 Lack of exception handling 7 Lack of use of interfaces or abstract classes 8 Use of mulitple return types 9 Inconsistent variable naming | t | f | f | . Long method2. Feature envy3. Code duplication4. Primitive obsession 5. Lack of encapsulation 6. Lack of exception handling 7. Lack of use of interfaces or abstract classes 8. Use of mulitple return types 9. Inconsistent variable naming | blob | 0 | 5924 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/DirectExecutorService.java/#L37-L252 | 2 | 594 | 5924 | minor |
| 193 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | f | f | f | data class | 0 | 2220 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 2 | 193 | 2220 | minor | |||
| 3581 | { "input": { "codeSmells": ["Blob", "Data Class", "Feature Envy", "Long Method"], "code": "public class MyClass {\n private int x;\n\n public void setX(int x) {\n this.x = x;\n }\n\n public int getX() {\n return x;\n }\n}" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": "the bad smells are: 3. Data Class" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class | t | t | f | message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class | feature envy | 0 | 7900 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/service/cpi/SharingRegistryService.java/#L41810-L41827 | 1 | 3581 | 7900 | minor |
| 165 | { "response": "YES I found bad smells", "bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConfigurationListener extends Phase implements org.osgi.service.cm.ConfigurationListener { public static class Builder { public Builder(ContainerState containerState) { _containerState = containerState; } public Builder component(Component component) { _component = component; return this; } public ConfigurationListener build() { Objects.requireNonNull(_component); return new ConfigurationListener(_containerState, _component); } private Component _component; private final ContainerState _containerState; } protected ConfigurationListener( ContainerState containerState, Component component) { super(containerState, component); _component = component; _log = containerState.containerLogs().getLogger(getClass()); } @Override public boolean close() { try (Syncro open = syncro.open()) { if (_listenerService != null) { _listenerService.unregister(); _listenerService = null; } return next.map( next -> { submit(next.closeOp(), next::close).onFailure( f -> { _log.error(l -> l.error("CCR Failure in configuration listener close on {}", next, f)); error(f); } ); return true; } ).orElse(true); } } @Override public Op closeOp() { return Op.of(Mode.CLOSE, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public void configurationEvent(ConfigurationEvent event) { next.map(next -> (Component)next).ifPresent( next -> next.configurationTemplates().stream().filter( t -> Predicates.isMatchingConfiguration(event).test(t) ).findFirst().ifPresent( t -> { String eventString = Arrays.asList(event.getPid(), event.getFactoryPid(), type(event)).toString(); Promise result = containerState.submit( Op.of(Mode.OPEN, Type.CONFIGURATION_EVENT, eventString), () -> { _log.debug(l -> l.debug("CCR Event {} matched {} because of {}", eventString, _component.template().name, _component.template().configurations)); processEvent(next, t, event); return true; } ); try { result.getValue(); } catch (Exception e) { Throw.exception(e); } } ) ); } @Override public boolean open() { try (Syncro open = syncro.open()) { if (containerState.bundleContext() == null) { // this bundle was already removed return false; } Dictionary properties = new Hashtable<>(); properties.put("name", toString()); properties.put(Constants.SERVICE_DESCRIPTION, "Aries CDI - Configuration Listener for " + containerState.bundle()); properties.put(Constants.SERVICE_VENDOR, "Apache Software Foundation"); _listenerService = containerState.bundleContext().registerService( org.osgi.service.cm.ConfigurationListener.class, this, properties); return next.map(next -> (Component)next).map( component -> { submit(component.openOp(), component::open).then( s -> { component.configurationTemplates().stream().filter( ct -> Objects.nonNull(ct.pid) ).forEach( template -> { if (template.maximumCardinality == MaximumCardinality.ONE) { containerState.findConfig(template.pid).ifPresent( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, null, c.getPid())) ); } else { containerState.findConfigs(template.pid, true).ifPresent( arr -> Arrays.stream(arr).forEach( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, c.getFactoryPid(), c.getPid())) ) ); } } ); return s; }, f -> { _log.error(l -> l.error("CCR Failure during configuration start on {}", next, f.getFailure())); error(f.getFailure()); } ); return true; } ).orElse(true); } } @Override public Op openOp() { return Op.of(Mode.OPEN, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public String toString() { return Arrays.asList(getClass().getSimpleName(), _component).toString(); } private void processEvent(Component component, ConfigurationTemplateDTO t, ConfigurationEvent event) { boolean required = t.policy == ConfigurationPolicy.REQUIRED; boolean single = t.maximumCardinality == MaximumCardinality.ONE; switch (event.getType()) { case ConfigurationEvent.CM_DELETED: component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { if (!required) { instance.configurations.removeIf( c -> c.template == t ); submit(instance.openOp(), instance::open); } else { component.instances().remove(instance); } return s; } ); } ); return; case ConfigurationEvent.CM_LOCATION_CHANGED: break; case ConfigurationEvent.CM_UPDATED: if (!single && !component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> event.getPid().equals(instance.pid) ).findFirst().isPresent()) { ExtendedComponentInstanceDTO instance = new ExtendedComponentInstanceDTO( containerState, _component.activatorBuilder()); instance.activations = new CopyOnWriteArrayList<>(); instance.configurations = new CopyOnWriteArrayList<>(); instance.pid = event.getPid(); instance.references = new CopyOnWriteArrayList<>(); instance.template = component.template(); component.instances().add(instance); } containerState.findConfig(event.getPid()).ifPresent( configuration -> { ExtendedConfigurationDTO configurationDTO = new ExtendedConfigurationDTO(); configurationDTO.configuration = configuration; configurationDTO.pid = configuration.getPid(); configurationDTO.properties = Maps.of(configuration.getProcessedProperties(event.getReference())); configurationDTO.template = t; component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { instance.configurations.removeIf(c -> c.template == t); instance.configurations.add(configurationDTO); submit(instance.openOp(), instance::open); return s; } ); } ); } ); break; } } private String type(ConfigurationEvent event) { if (event.getType() == ConfigurationEvent.CM_DELETED) return "DELETED"; if (event.getType() == ConfigurationEvent.CM_LOCATION_CHANGED) return "LOCATION_CHANGED"; if (event.getType() == ConfigurationEvent.CM_UPDATED) return "UPDATED"; throw new IllegalArgumentException("CM Event type " + event.getType()); } private volatile ServiceRegistration _listenerService; private final Component _component; private final Logger _log; } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2008 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/ConfigurationListener.java/#L42-L310 | 2 | 165 | 2008 | critical |
| 1482 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | long method | t | t | f | long method | data class | 0 | 11083 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 1 | 1482 | 11083 | minor |
| 724 | YES I found bad smells 1. Long method 2. Feature envy the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: { Tuple2 val = arg0.next(); long valix = val._2 + 1; long rix = UtilFunctions.computeBlockIndex(valix, _brlen); int pos = UtilFunctions.computeCellInBlock(valix, _brlen); if( ix == null || ix.getRowIndex() != rix ) { if( ix !=null ) ret.add(new Tuple2<>(ix,mb)); long len = UtilFunctions.computeBlockSize(_rlen, rix, _brlen); ix = new MatrixIndexes(rix,1); mb = new MatrixBlock((int)len, 1, false); } mb.quickSetValue(pos, 0, val._1); } //flush last block if( mb!=null && mb.getNonZeros() != 0 ) ret.add(new Tuple2<>(ix,mb)); return ret.iterator(); } } private static class ConvertToBinaryBlockFunction2 implements PairFlatMapFunction>,MatrixIndexes,MatrixBlock> { private static final long serialVersionUID = -8638434373377180192L; private long _rlen = -1; private int _brlen = -1; public ConvertToBinaryBlockFunction2(long rlen, int brlen) { _rlen = rlen; _brlen = brlen; } public Iterator> call(Iterator> arg0) throws Exception { ArrayList> ret = new ArrayList<>(); MatrixIndexes ix = null; MatrixBlock mb = null; |
blob | Long method2 Feature envythe bad smells are: | t | f | f | . Long method2. Feature envythe bad smells are: | blob | 0 | 6835 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDSortUtils.java/#L431-L475 | 2 | 724 | 6835 | minor |
| 4664 | { "message": "YES I found bad smells", "bad_smells_found": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12456 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 4664 | 12456 | minor |
| 2591 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
blob | data class | t | t | f | data class | blob | 0 | 14999 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 1 | 2591 | 14999 | minor |
| 1560 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | t | f | f | blob | 0 | 11305 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 1 | 1560 | 11305 | major | ||
| 2516 | {"message": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | long method | t | t | f | long method | data class | 0 | 14697 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 2516 | 14697 | major |
| 871 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7972 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 871 | 7972 | minor |
| 39 | {"response": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 767 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 2 | 39 | 767 | critical |
| 677 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6583 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 2 | 677 | 6583 | minor |
| 114 | { "response": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method | t | t | f | long method | data class | 0 | 1489 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 114 | 1489 | critical |
| 5419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15209 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 5419 | 15209 | minor |
| 707 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 6736 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 707 | 6736 | minor |
| 1389 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | 'Long Method' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',o,n,g," ",M,t,h,o,d,'} | 0 | 10840 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1389 | 10840 | major |
| 1307 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | long method | t | t | f | long method | blob | 0 | 10676 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 1 | 1307 | 10676 | minor |
| 5764 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14546 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5764 | 14546 | minor |
| 1374 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10804 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 1374 | 10804 | major |
| 2567 | YES, I found bad smells 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14871 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 2 | 2567 | 14871 | minor |
| 2123 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 13215 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 2 | 2123 | 13215 | major |
| 2639 | { "input_code": "public class Calculator {\n private int number1;\n private int number2;\n\n public Calculator(int number1, int number2) {\n this.number1 = number1;\n this.number2 = number2;\n }\n\n public int add() {\n return number1 + number2;\n }\n\n public int multiply() {\n return number1 * number2;\n }\n}", "code_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | false | 0 | 15142 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2639 | 15142 | minor | ||
| 411 | { "response": "YES I found bad smells", "bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ParserRule getCollectionTypeIdentifierRule() { return getCollectionTypeIdentifierAccess().getRule(); } |
feature envy | blob | t | t | f | blob | feature envy | 0 | 4212 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L3702-L3704 | 1 | 411 | 4212 | minor |
| 149 | {"response": "YES I found bad smells", "the bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class OgnlHelper { private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); private OgnlHelper() { } /** * Tests whether or not the given String is a Camel OGNL expression. * * An expression is considered an OGNL expression when it contains either one of the following chars: . or [ * * @param expression the String * @return true if a Camel OGNL expression, otherwise false. */ public static boolean isValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } // the brackets should come in a pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 && bracketEnd > 0) { return bracketBegin == bracketEnd; } return expression.contains("."); } public static boolean isInvalidValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) { return false; } // the brackets should come in pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 || bracketEnd > 0) { return bracketBegin != bracketEnd; } // check for double dots if (expression.contains("..")) { return true; } return false; } /** * Validates whether the method name is using valid java identifiers in the name * Will throw {@link IllegalArgumentException} if the method name is invalid. */ public static void validateMethodName(String method) { if (ObjectHelper.isEmpty(method)) { return; } for (int i = 0; i < method.length(); i++) { char ch = method.charAt(i); if (i == 0 && '.' == ch) { // its a dot before a method name continue; } if (ch == '(' || ch == '[' || ch == '.' || ch == '?') { // break when method name ends and sub method or arguments begin break; } if (i == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method); } } } /** * Tests whether or not the given Camel OGNL expression is using the null safe operator or not. * * @param ognlExpression the Camel OGNL expression * @return true if the null safe operator is used, otherwise false. */ public static boolean isNullSafeOperator(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return false; } return ognlExpression.startsWith("?"); } /** * Removes any leading operators from the Camel OGNL expression. * * Will remove any leading of the following chars: ? or . * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any leading operators. */ public static String removeLeadingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.startsWith("?")) { ognlExpression = ognlExpression.substring(1); } if (ognlExpression.startsWith(".")) { ognlExpression = ognlExpression.substring(1); } return ognlExpression; } /** * Removes any trailing operators from the Camel OGNL expression. * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any trailing operators. */ public static String removeTrailingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.contains("[")) { return StringHelper.before(ognlExpression, "["); } return ognlExpression; } public static String removeOperators(String ognlExpression) { return removeLeadingOperators(removeTrailingOperators(ognlExpression)); } public static KeyValueHolder isOgnlIndex(String ognlExpression) { Matcher matcher = INDEX_PATTERN.matcher(ognlExpression); if (matcher.matches()) { // to avoid empty strings as we want key/value to be null in such cases String key = matcher.group(1); if (ObjectHelper.isEmpty(key)) { key = null; } // to avoid empty strings as we want key/value to be null in such cases String value = matcher.group(2); if (ObjectHelper.isEmpty(value)) { value = null; } return new KeyValueHolder<>(key, value); } return null; } /** * Regular expression with repeating groups is a pain to get right * and then nobody understands the reg exp afterwards. * So we use a bit ugly/low-level Java code to split the OGNL into methods. * * @param ognl the ognl expression * @return a list of methods, will return an empty list, if ognl expression has no methods * @throws IllegalArgumentException if the last method has a missing ending parenthesis */ public static List splitOgnl(String ognl) { List methods = new ArrayList<>(); // return an empty list if ognl is empty if (ObjectHelper.isEmpty(ognl)) { return methods; } StringBuilder sb = new StringBuilder(); int j = 0; // j is used as counter per method boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo] boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo}) for (int i = 0; i < ognl.length(); i++) { char ch = ognl.charAt(i); // special for starting a new method if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?') || (ch != '.' && ch != '?' && ch != ']')) { sb.append(ch); // special if we are doing square bracket if (ch == '[' && !parenthesisBracket) { squareBracket = true; } else if (ch == '(') { parenthesisBracket = true; } else if (ch == ')') { parenthesisBracket = false; } j++; // advance } else { if (ch == '.' && !squareBracket && !parenthesisBracket) { // only treat dot as a method separator if not inside a square bracket block // as dots can be used in key names when accessing maps // a dit denotes end of this method and a new method is to be invoked String s = sb.toString(); // reset sb sb.setLength(0); // pass over ? to the new method if (s.endsWith("?")) { sb.append("?"); s = s.substring(0, s.length() - 1); } // add the method methods.add(s); // reset j to begin a new method j = 0; } else if (ch == ']' && !parenthesisBracket) { // append ending ] to method name sb.append(ch); String s = sb.toString(); // reset sb sb.setLength(0); // add the method methods.add(s); // reset j to begin a new method j = 0; // no more square bracket squareBracket = false; } // and don't lose the char if its not an ] end marker (as we already added that) if (ch != ']' || parenthesisBracket) { sb.append(ch); } // only advance if already begun on the new method if (j > 0) { j++; } } } // add remainder in buffer when reached end of data if (sb.length() > 0) { methods.add(sb.toString()); } String last = methods.isEmpty() ? null : methods.get(methods.size() - 1); if (parenthesisBracket && last != null) { // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis if (last.contains("(") && !last.endsWith(")")) { throw new IllegalArgumentException("Method should end with parenthesis, was " + last); } } return methods; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 1873 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-util/src/main/java/org/apache/camel/util/OgnlHelper.java/#L27-L292 | 1 | 149 | 1873 | major |
| 2546 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 14791 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 2546 | 14791 | major |
| 1776 | YES I found bad smells the bad smells are: 1. Inconsistent formatting and indentation, 2. Lack of comments or description of code/variables, 3. Unnecessary import statements, 4. Long method, 5. Feature envy, 6. Redundancy/Elimination of repeated code, 7. Violation of the Single Responsibility Principle (SRP), 8. Unnecessary use of superfluous boolean variables, 9. Use of hard-coded values instead of constants. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Inconsistent formatting and indentation, 2 Lack of comments or description of code/variables, 3 Unnecessary import statements, 4 Long method, 5 Feature envy, 6 Redundancy/Elimination of repeated code, 7 Violation of the Single Responsibility Principle (SRP), 8 Unnecessary use of superfluous boolean variables, 9 Use of hard-coded values instead of constants | t | f | f | . Inconsistent formatting and indentation, 2. Lack of comments or description of code/variables, 3. Unnecessary import statements, 4. Long method, 5. Feature envy, 6. Redundancy/Elimination of repeated code, 7. Violation of the Single Responsibility Principle (SRP), 8. Unnecessary use of superfluous boolean variables, 9. Use of hard-coded values instead of constants. | data class | 0 | 11956 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 1776 | 11956 | major |
| 2569 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14876 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2569 | 14876 | major |
| 459 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4459 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 459 | 4459 | minor |
| 703 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6698 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 703 | 6698 | major |
| 2579 | YES I found bad smells The bad smells are: 1. Duplicate code, 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | Duplicate code, 2 Long method | t | f | f | . Duplicate code, 2. Long method | data class | 0 | 14944 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 2579 | 14944 | major |
| 547 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
data class | f | f | f | data class | 0 | 5553 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 1 | 547 | 5553 | critical | ||
| 1889 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } |
blob | data class | t | t | f | data class | blob | 0 | 12304 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 | 1 | 1889 | 12304 | minor |
| 2601 | {"answer": "YES I found bad smells, the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 15019 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 1 | 2601 | 15019 | major |
| 201 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IgnoreCommitOptimizeUpdateProcessorFactory extends UpdateRequestProcessorFactory { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String DEFAULT_RESPONSE_MSG = "Explicit commit/optimize requests are forbidden!"; protected ErrorCode errorCode; protected String responseMsg; protected boolean ignoreOptimizeOnly = false; // default behavior is to ignore commits and optimize @Override public void init(final NamedList args) { SolrParams params = (args != null) ? args.toSolrParams() : null; if (params == null) { errorCode = ErrorCode.FORBIDDEN; // default is 403 error responseMsg = DEFAULT_RESPONSE_MSG; ignoreOptimizeOnly = false; return; } ignoreOptimizeOnly = params.getBool("ignoreOptimizeOnly", false); int statusCode = params.getInt("statusCode", ErrorCode.FORBIDDEN.code); if (statusCode == 200) { errorCode = null; // not needed but makes the logic clearer responseMsg = params.get("responseMessage"); // OK to be null for 200's } else { errorCode = ErrorCode.getErrorCode(statusCode); if (errorCode == ErrorCode.UNKNOWN) { // only allow the error codes supported by the SolrException.ErrorCode class StringBuilder validCodes = new StringBuilder(); int appended = 0; for (ErrorCode code : ErrorCode.values()) { if (code != ErrorCode.UNKNOWN) { if (appended++ > 0) validCodes.append(", "); validCodes.append(code.code); } } throw new IllegalArgumentException("Configured status code " + statusCode + " not supported! Please choose one of: " + validCodes.toString()); } // must always have a response message if sending an error code responseMsg = params.get("responseMessage", DEFAULT_RESPONSE_MSG); } } @Override public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) { return new IgnoreCommitOptimizeUpdateProcessor(rsp, this, next); } static class IgnoreCommitOptimizeUpdateProcessor extends UpdateRequestProcessor { private final SolrQueryResponse rsp; private final ErrorCode errorCode; private final String responseMsg; private final boolean ignoreOptimizeOnly; IgnoreCommitOptimizeUpdateProcessor(SolrQueryResponse rsp, IgnoreCommitOptimizeUpdateProcessorFactory factory, UpdateRequestProcessor next) { super(next); this.rsp = rsp; this.errorCode = factory.errorCode; this.responseMsg = factory.responseMsg; this.ignoreOptimizeOnly = factory.ignoreOptimizeOnly; } @Override public void processCommit(CommitUpdateCommand cmd) throws IOException { if (ignoreOptimizeOnly && !cmd.optimize) { // we're setup to only ignore optimize requests so it's OK to pass this commit on down the line if (next != null) next.processCommit(cmd); return; } if (cmd.getReq().getParams().getBool(DistributedUpdateProcessor.COMMIT_END_POINT, false)) { // this is a targeted commit from replica to leader needed for recovery, so can't be ignored if (next != null) next.processCommit(cmd); return; } final String cmdType = cmd.optimize ? "optimize" : "commit"; if (errorCode != null) { IgnoreCommitOptimizeUpdateProcessorFactory.log.info( "{} from client application ignored with error code: {}", cmdType, errorCode.code); rsp.setException(new SolrException(errorCode, responseMsg)); } else { // errorcode is null, treat as a success with an optional message warning the commit request was ignored IgnoreCommitOptimizeUpdateProcessorFactory.log.info( "{} from client application ignored with status code: 200", cmdType); if (responseMsg != null) { NamedList responseHeader = rsp.getResponseHeader(); if (responseHeader != null) { responseHeader.add("msg", responseMsg); } else { responseHeader = new SimpleOrderedMap(); responseHeader.add("msg", responseMsg); rsp.addResponseHeader(responseHeader); } } } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2246 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/IgnoreCommitOptimizeUpdateProcessorFactory.java/#L42-L148 | 1 | 201 | 2246 | major |
| 1904 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Inappropriate intimacy, 4. Data clumps, 5. Large class, 6. Long parameter list, 7. Duplicate code, 8. Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | Long method, 2 Feature envy, 3 Inappropriate intimacy, 4 Data clumps, 5 Large class, 6 Long parameter list, 7 Duplicate code, 8 Message chains | t | f | f | . Long method, 2. Feature envy, 3. Inappropriate intimacy, 4. Data clumps, 5. Large class, 6. Long parameter list, 7. Duplicate code, 8. Message chains | blob | 0 | 12369 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 2 | 1904 | 12369 | major |
| 529 | YES I found bad smells the bad smells are: 1. Feature Envy - The SignatureHashBuilder class heavily relies on external classes and methods. 2. Long Method - The methods within the SignatureHashBuilder class are long and perform multiple tasks, making it difficult to read and maintain. 3. Inappropriate Intimacy - The SignatureHashBuilder class has tight coupling with the AnnotationSignatureRelevanceUtil and JvmDeclaredTypeSignatureHashProvider classes. 4. Inconsistent Naming - Some methods use different naming conventions, making the code less readable. 5. Magic Number - The MessageDigest.getInstance("MD5") call uses a magic number without explanation. 6. Exception Handling - The exception handling in the createDigest() and hash() methods is not clear and could potentially cause issues. 7. Redundant Code - The constructor and the hash() method have redundant code that can be refactored. 8. Switch Statements - The use of switch statements in the appendVisibility and appendTypeParameter methods can make the code more complex and harder to maintain. 9. Simultaneous Update - The append() method in the appendMemberSignatures() method makes simultaneous updates to the same object, which could potentially cause issues. 10. Lack of Comments - There are no comments in the code, making it difficult to understand the purpose and functionality of each method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | Feature Envy - The SignatureHashBuilder class heavily relies on external classes and methods 2 Long Method - The methods within the SignatureHashBuilder class are long and perform multiple tasks, making it difficult to read and maintain 3 Inappropriate Intimacy - The SignatureHashBuilder class has tight coupling with the AnnotationSignatureRelevanceUtil and JvmDeclaredTypeSignatureHashProvider classes 4 Inconsistent Naming - Some methods use different naming conventions, making the code less readable 5 Magic Number - The MessageDigestgetInstance("MD5") call uses a magic number without explanation 6 Exception Handling - The exception handling in the createDigest() and hash() methods is not clear and could potentially cause issues 7 Redundant Code - The constructor and the hash() method have redundant code that can be refactored 8 Switch Statements - The use of switch statements in the appendVisibility and appendTypeParameter methods can make the code more complex and harder to maintain 9 Simultaneous Update - The append() method in the appendMemberSignatures() method makes simultaneous updates to the same object, which could potentially cause issues | t | f | f | . Feature Envy - The SignatureHashBuilder class heavily relies on external classes and methods. 2. Long Method - The methods within the SignatureHashBuilder class are long and perform multiple tasks, making it difficult to read and maintain. 3. Inappropriate Intimacy - The SignatureHashBuilder class has tight coupling with the AnnotationSignatureRelevanceUtil and JvmDeclaredTypeSignatureHashProvider classes. 4. Inconsistent Naming - Some methods use different naming conventions, making the code less readable. 5. Magic Number - The MessageDigest.getInstance("MD5") call uses a magic number without explanation. 6. Exception Handling - The exception handling in the createDigest() and hash() methods is not clear and could potentially cause issues. 7. Redundant Code - The constructor and the hash() method have redundant code that can be refactored. 8. Switch Statements - The use of switch statements in the appendVisibility and appendTypeParameter methods can make the code more complex and harder to maintain. 9. Simultaneous Update - The append() method in the appendMemberSignatures() method makes simultaneous updates to the same object, which could potentially cause issues. | blob | 0 | 5454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 2 | 529 | 5454 | minor |
| 1798 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component("org.apache.usergrid.rest.management.organizations.applications.ApplicationResource") @Scope("prototype") @Produces({ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", "text/jscript" }) public class ApplicationResource extends AbstractContextResource { private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); public static final String CONFIRM_APPLICATION_IDENTIFIER = "confirm_application_identifier"; public static final String RESTORE_PASSWORD = "restore_password"; //@Autowired //protected ExportService exportService; OrganizationInfo organization; UUID applicationId; ApplicationInfo application; @Autowired private SignInProviderFactory signInProviderFactory; public ApplicationResource() { } public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { this.organization = organization; this.applicationId = applicationId; return this; } public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { this.organization = organization; applicationId = application.getId(); this.application = application; return this; } @RequireOrganizationAccess @GET @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getApplication( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); ServiceManager sm = smf.getServiceManager( applicationId ); response.setAction( "get" ); response.setApplication( sm.getApplication() ); response.setParams( ui.getQueryParameters() ); response.setResults( management.getApplicationMetadata( applicationId ) ); return response; } @RequireOrganizationAccess @GET @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get application client credentials"); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.getClientSecretForApplication( applicationId ) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @POST @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse generateCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "generate application client credentials" ); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.newClientSecretForApplication(applicationId) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @GET @JSONP @Path("_size") public ApiResponse getApplicationSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "get application size for all entities" ); long size = management.getApplicationSize(this.applicationId); Map map = new HashMap<>(); Map innerMap = new HashMap<>(); Map sumMap = new HashMap<>(); innerMap.put("application",size); sumMap.put("size",innerMap); map.put("aggregation", sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("{collection_name}/_size") public ApiResponse getCollectionSize( @Context UriInfo ui, @PathParam( "collection_name" ) String collection_name, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); long size = management.getCollectionSize(this.applicationId, collection_name); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); Map innerMap = new HashMap<>(); innerMap.put(collection_name,size); sumMap.put("size",innerMap); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("collections/_size") public ApiResponse getEachCollectionSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); Map sizes = management.getEachCollectionSize(this.applicationId); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); sumMap.put("size",sizes); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @POST @Path("sia-provider") @Consumes(APPLICATION_JSON) @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, Map json, @QueryParam("callback") @DefaultValue("") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "post signin provider configuration" ); Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); SignInAsProvider signInAsProvider = null; if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { signInAsProvider = signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { signInAsProvider = signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { signInAsProvider = signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); } Preconditions.checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); signInAsProvider.saveToConfiguration( json ); return response; } // @POST // @Path("export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // // UUID jobUUID = null; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( bucketName == null ) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // json.put("organizationId", organization.getUuid()); // json.put( "applicationId",applicationId); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // catch ( Exception e ) { // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // return Response.status( SC_INTERNAL_SERVER_ERROR ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // @POST // @Path("collection/{collection_name}/export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui, // @PathParam( "collection_name" ) String collection_name ,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // UUID jobUUID = null; // String colExport = collection_name; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // //checkJsonExportProperties(json); // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // if(bucketName == null) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // // json.put( "organizationId",organization.getUuid() ); // json.put( "applicationId", applicationId); // json.put( "collectionName", colExport); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ) // .build(); // } // catch ( Exception e ) { // // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // // OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_INTERNAL_SERVER_ERROR ) // .setErrorDescription( e.getMessage() ) // .buildJSONMessage(); // // return Response.status( errorMsg.getResponseStatus() ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ) // .build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // // @Path( "imports" ) // public ImportsResource importGetJson( @Context UriInfo ui, // @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) // throws Exception { // // // return getSubResource( ImportsResource.class ).init( organization, application ); // } @GET @Path("/status") public Response getStatus() { Map statusMap = new HashMap(); EntityManager em = emf.getEntityManager( applicationId ); if ( !emf.getIndexHealth().equals( Health.RED ) ) { statusMap.put("message", "Index Health Status RED for application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } try { if ( em.getApplication() == null ) { statusMap.put("message", "Application " + applicationId + " not found"); return Response.status( SC_NOT_FOUND ).entity( statusMap ).build(); } } catch (Exception ex) { statusMap.put("message", "Error looking up application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } return Response.status( SC_OK ).entity( null ).build(); } /** * Put on application URL will restore application if it was deleted. */ @PUT @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executePut( @Context UriInfo ui, String body, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if ( applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (!SubjectUtils.isServiceAdmin()) { // require password if it exists String storedRestorePassword = restorePasswordService.getApplicationRestorePassword(applicationId); if (StringUtils.isNotEmpty(storedRestorePassword)) { // must have matching password as query parameter String suppliedRestorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (!storedRestorePassword.equals(suppliedRestorePassword)) { throw new IllegalArgumentException("Application cannot be restored without application password"); } } } management.restoreApplication( applicationId ); // not deleting password -- will be changed upon successful soft delete ApiResponse response = createApiResponse(); response.setAction( "restore" ); response.setApplication( emf.getEntityManager( applicationId ).getApplication() ); response.setParams( ui.getQueryParameters() ); return response; } /** * Caller MUST pass confirm_application_identifier that is either the UUID or the * name of the application to be deleted. Yes, this is redundant and intended to * be a protection measure to force caller to confirm that they want to do a delete. */ @DELETE @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executeDelete( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback, @QueryParam(CONFIRM_APPLICATION_IDENTIFIER) String confirmApplicationIdentifier) throws Exception { if ( application == null && applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } // If the path uses name then expect name, otherwise if they use uuid then expect uuid. if (application == null) { if (!applicationId.toString().equals( confirmApplicationIdentifier )) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application id."); } } else if (!application.getName().split( "/" )[1].equals( confirmApplicationIdentifier ) ) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application name"); } String restorePassword = null; ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (SubjectUtils.isServiceAdmin()) { restorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (StringUtils.isNotEmpty(restorePassword)) { // save password, required for future undelete if not sysadmin restorePasswordService.setApplicationRestorePassword(applicationId, restorePassword); } } management.deleteApplication( applicationId ); if (restorePassword == null) { // clear restore password restorePasswordService.removeApplicationRestorePassword(applicationId); } if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() deleted appId = {}", applicationId); } ApiResponse response = createApiResponse(); response.setAction( "delete" ); response.setApplication(emf.getEntityManager( applicationId ).getApplication()); response.setParams(ui.getQueryParameters()); if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() sending response "); } return response; } private ApplicationRestorePasswordService getApplicationRestorePasswordService() { return injector.getInstance(ApplicationRestorePasswordService.class); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12006 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/rest/src/main/java/org/apache/usergrid/rest/management/organizations/applications/ApplicationResource.java/#L63-L563 | 1 | 1798 | 12006 | major |
| 1300 | {"message": "YES I found bad smells", "detected_bad_smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | long method | t | t | f | long method | blob | 0 | 10650 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 1300 | 10650 | major |
| 409 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4159 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 409 | 4159 | critical |
| 3367 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 6393 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 3367 | 6393 | minor | ||
| 2457 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14527 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 1 | 2457 | 14527 | minor |
| 2064 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long method, 2. Data class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 12979 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 | 1 | 2064 | 12979 | minor |
| 1321 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10698 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 1321 | 10698 | minor |
| 933 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 8372 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 2 | 933 | 8372 | minor |
| 2517 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14699 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 2 | 2517 | 14699 | major |
| 707 | YES I found bad smells. The bad smells are: 1. Long class 2. Feature envy 3. Shotgun surgery 4. Duplicated code 5. Dead code 6. Long parameter list 7. Primitive obsession 8. Data clumps 9. Inappropriate intimacy 10. Message chains 11. Large class 12. God class 13. Comments 14. Lazy class 15. Switch statements 16. Magic numbers 17. Data clumps 18. Incomplete library class 19. Data class 20. Constructor with multiple parameters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
blob | Long class2 Feature envy3 Shotgun surgery4 Duplicated code5 Dead code6 Long parameter list7 Primitive obsession8 Data clumps9 Inappropriate intimacy | t | f | f | . Long class2. Feature envy3. Shotgun surgery4. Duplicated code5. Dead code6. Long parameter list7. Primitive obsession8. Data clumps9. Inappropriate intimacy | blob | 0 | 6736 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 707 | 6736 | minor |
| 604 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6027 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 604 | 6027 | major |
| 1782 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy, 3. Bloated class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
blob | Long method, 2Feature envy, 3 Bloated class | t | f | f | .Long method, 2.Feature envy, 3. Bloated class | blob | 0 | 11964 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 2 | 1782 | 11964 | major |
| 987 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Duplicate code2 Inconsistent naming conventions | t | f | f | . Duplicate code2. Inconsistent naming conventions | data class | 0 | 8965 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 2 | 987 | 8965 | critical |
| 1274 | YES I found bad smells: 1. Long method 2. Feature envy 3. Magic numbers/strings 4. Inappropriate naming (ex: "metaUrl" instead of "metadataUrl") 5. Poor encapsulation (ex: accessing instance variables directly in the execute() method instead of using getter/setter methods) 6. Code duplication (ex: creating and adding the same Options object in the constructor and getOptions() method) 7. Excessive use of static methods 8. Complex and unclear logic in the execute() method 9. Potential concurrency issues with the use of "initialized" boolean flag in the ReEncodeCuboidFunction inner class 10. Possible violation of the Single Responsibility Principle with the SparkCubingMerge class handling both command line options and executing the merge job. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | Long method2 Feature envy3 Magic numbers/strings4 Inappropriate naming (ex: "metaUrl" instead of "metadataUrl") 5 Poor encapsulation (ex: accessing instance variables directly in the execute() method instead of using getter/setter methods)6 Code duplication (ex: creating and adding the same Options object in the constructor and getOptions() method)7 Excessive use of static methods 8 Complex and unclear logic in the execute() method 9 Potential concurrency issues with the use of "initialized" boolean flag in the ReEncodeCuboidFunction inner class | t | f | f | . Long method2. Feature envy3. Magic numbers/strings4. Inappropriate naming (ex: "metaUrl" instead of "metadataUrl") 5. Poor encapsulation (ex: accessing instance variables directly in the execute() method instead of using getter/setter methods)6. Code duplication (ex: creating and adding the same Options object in the constructor and getOptions() method)7. Excessive use of static methods 8. Complex and unclear logic in the execute() method 9. Potential concurrency issues with the use of "initialized" boolean flag in the ReEncodeCuboidFunction inner class | blob | 0 | 10582 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 2 | 1274 | 10582 | major |
| 293 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public class SingleThreadAccessCheckingTypeSerializer extends TypeSerializer { private static final long serialVersionUID = 131020282727167064L; private final SingleThreadAccessChecker singleThreadAccessChecker; private final TypeSerializer originalSerializer; public SingleThreadAccessCheckingTypeSerializer(TypeSerializer originalSerializer) { this.singleThreadAccessChecker = new SingleThreadAccessChecker(); this.originalSerializer = originalSerializer; } @Override public boolean isImmutableType() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.isImmutableType(); } } @Override public TypeSerializer duplicate() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializer<>(originalSerializer.duplicate()); } } @Override public T createInstance() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.createInstance(); } } @Override public T copy(T from) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from); } } @Override public T copy(T from, T reuse) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from, reuse); } } @Override public int getLength() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.getLength(); } } @Override public void serialize(T record, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.serialize(record, target); } } @Override public T deserialize(DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(source); } } @Override public T deserialize(T reuse, DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(reuse, source); } } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.copy(source, target); } } @Override public boolean equals(Object obj) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return obj == this || (obj != null && obj.getClass() == getClass() && originalSerializer.equals(obj)); } } @Override public int hashCode() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.hashCode(); } } @Override public TypeSerializerSnapshot snapshotConfiguration() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializerSnapshot<>(this); } } public static class SingleThreadAccessCheckingTypeSerializerSnapshot extends CompositeTypeSerializerSnapshot> { @SuppressWarnings({"unchecked", "unused"}) public SingleThreadAccessCheckingTypeSerializerSnapshot() { super((Class>) (Class) SingleThreadAccessCheckingTypeSerializer.class); } SingleThreadAccessCheckingTypeSerializerSnapshot(SingleThreadAccessCheckingTypeSerializer serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return 1; } @Override protected TypeSerializer[] getNestedSerializers(SingleThreadAccessCheckingTypeSerializer outerSerializer) { return new TypeSerializer[] { outerSerializer.originalSerializer }; } @SuppressWarnings("unchecked") @Override protected SingleThreadAccessCheckingTypeSerializer createOuterSerializerWithNestedSerializers( TypeSerializer[] nestedSerializers) { return new SingleThreadAccessCheckingTypeSerializer<>((TypeSerializer) nestedSerializers[0]); } } private void writeObject(ObjectOutputStream outputStream) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { outputStream.defaultWriteObject(); } } private static class SingleThreadAccessChecker implements Serializable { private static final long serialVersionUID = 131020282727167064L; private transient AtomicReference currentThreadRef = new AtomicReference<>(); SingleThreadAccessCheck startSingleThreadAccessCheck() { assert(currentThreadRef.compareAndSet(null, Thread.currentThread())) : "The checker has concurrent access from " + currentThreadRef.get(); return new SingleThreadAccessCheck(currentThreadRef); } private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { inputStream.defaultReadObject(); currentThreadRef = new AtomicReference<>(); } } private static class SingleThreadAccessCheck implements AutoCloseable { private final AtomicReference currentThreadRef; private SingleThreadAccessCheck(AtomicReference currentThreadRef) { this.currentThreadRef = currentThreadRef; } @Override public void close() { assert(currentThreadRef.compareAndSet(Thread.currentThread(), null)) : "The checker has concurrent access from " + currentThreadRef.get(); } } } |
blob | long method | t | t | f | long method | blob | 0 | 3080 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/SingleThreadAccessCheckingTypeSerializer.java/#L31-L203 | 1 | 293 | 3080 | minor |
| 725 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
blob | Long method2 Feature envy3 Data class4 Shotgun surgery | t | f | f | . Long method2. Feature envy3. Data class4. Shotgun surgery | blob | 0 | 6841 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 2 | 725 | 6841 | minor |
| 275 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.class, org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.Builder.class); } // Construct using org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); guaranteedTaskCount_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto getDefaultInstanceForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance(); } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto build() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto buildPartial() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = new org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.guaranteedTaskCount_ = guaranteedTaskCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) { return mergeFrom((org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto other) { if (other == org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance()) return this; if (other.hasGuaranteedTaskCount()) { setGuaranteedTaskCount(other.getGuaranteedTaskCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 guaranteed_task_count = 1; private int guaranteedTaskCount_ ; /** * optional int32 guaranteed_task_count = 1; */ public boolean hasGuaranteedTaskCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int32 guaranteed_task_count = 1; */ public int getGuaranteedTaskCount() { return guaranteedTaskCount_; } /** * optional int32 guaranteed_task_count = 1; */ public Builder setGuaranteedTaskCount(int value) { bitField0_ |= 0x00000001; guaranteedTaskCount_ = value; onChanged(); return this; } /** * optional int32 guaranteed_task_count = 1; */ public Builder clearGuaranteedTaskCount() { bitField0_ = (bitField0_ & ~0x00000001); guaranteedTaskCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:UpdateQueryRequestProto) } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 2954 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/llap-common/src/gen/protobuf/gen-java/org/apache/hadoop/hive/llap/plugin/rpc/LlapPluginProtocolProtos.java/#L286-L435 | 2 | 275 | 2954 | minor |
| 1966 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12599 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 2 | 1966 | 12599 | critical |
| 2383 | Yes I found bad smells 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent naming conventions 5. Code complexity and lack of modularity 6. Use of volatile variable 7. Mixing of different responsibilities in the same class (violating Single Responsibility Principle) 8. Use of synchronized blocks for thread safety instead of utilizing built-in thread-safe data structures. 9. Lack of comments and documentation for complex logic or code blocks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | Long method2 Feature envy3 Duplicated code 4 Inconsistent naming conventions5 Code complexity and lack of modularity6 Use of volatile variable7 Mixing of different responsibilities in the same class (violating Single Responsibility Principle)8 Use of synchronized blocks for thread safety instead of utilizing built-in thread-safe data structures9 Lack of comments and documentation for complex logic or code blocks | t | f | f | . Long method2. Feature envy3. Duplicated code 4. Inconsistent naming conventions5. Code complexity and lack of modularity6. Use of volatile variable7. Mixing of different responsibilities in the same class (violating Single Responsibility Principle)8. Use of synchronized blocks for thread safety instead of utilizing built-in thread-safe data structures.9. Lack of comments and documentation for complex logic or code blocks. | blob | 0 | 14341 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 2 | 2383 | 14341 | minor |
| 7 | { "output": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | Not specified | f | f | f | false | 0 | 573 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 2 | 7 | 573 | minor | |
| 1578 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
blob | data class | t | t | f | data class | blob | 0 | 11354 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 1578 | 11354 | minor |
| 1918 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12411 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 1 | 1918 | 12411 | major |
| 1945 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Not specified | f | f | f | false | 0 | 12515 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 1945 | 12515 | minor | |
| 1442 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10976 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 1442 | 10976 | minor |
| 127 | { "output": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1581 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 127 | 1581 | critical |
| 427 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
data class | long method | t | t | f | long method | data class | 0 | 4266 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 1 | 427 | 4266 | minor |
| 1424 | YES I found bad smells the bad smells are: 1. Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design. 2. Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain. 3. Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction. 4. Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality. 5. Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming. 6. Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design2 Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain3 Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction4 Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality5 Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming6 Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability | t | f | f | . Feature envy: The methods in the subclass all call methods in the parent class, indicating a potential problem with the OO design.2. Long method: The methods in the subclass are all relatively long and may be difficult to understand and maintain.3. Duplication: There is a lot of duplicated code in the methods, indicating a potential for refactoring and code reduction.4. Primitive obsession: The methods all deal with low-level socket options, rather than abstracting them into higher-level functionality.5. Resource acquisition is initialization (RAII) violation: The native library is loaded in the static block, rather than using RAII which is a more commonly accepted pattern in modern Java programming.6. Inappropriate separation of responsibilities: The subclass is responsible for both defining socket options and loading the native library, which could be separated into separate classes or responsibilities for better clarity and maintainability. | data class | 0 | 10935 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 2 | 1424 | 10935 | major |
| 1862 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @NbBundle.Messages({ "LocksFeatureUI_show=View by:", "LocksFeatureUI_aggregationByThreads=Threads", "LocksFeatureUI_aggregationByMonitors=Monitors", "LocksFeatureUI_aggregationHint=Results aggregation" }) abstract class LocksFeatureUI extends FeatureUI { private ProfilerToolbar toolbar; private LockContentionPanel locksView; // --- External implementation --------------------------------------------- abstract ProfilerClient getProfilerClient(); abstract void refreshResults(); // --- API implementation -------------------------------------------------- ProfilerToolbar getToolbar() { if (toolbar == null) initUI(); return toolbar; } JPanel getResultsUI() { if (locksView == null) initUI(); return locksView; } void sessionStateChanged(int sessionState) { refreshToolbar(sessionState); if (sessionState == Profiler.PROFILING_INACTIVE || sessionState == Profiler.PROFILING_IN_TRANSITION) { if (locksView != null) locksView.profilingSessionFinished(); } else if (sessionState == Profiler.PROFILING_RUNNING) { if (locksView != null) locksView.profilingSessionStarted(); } } void resetPause() { // if (lrPauseButton != null) lrPauseButton.setSelected(false); } void setForceRefresh() { if (locksView != null) locksView.setForceRefresh(true); } void refreshData() throws ClientUtils.TargetAppOrVMTerminated { if (locksView != null) locksView.refreshData(); } void resetData() { if (locksView != null) locksView.resetData(); } // --- UI ------------------------------------------------------------------ private JLabel shLabel; private ActionPopupButton shAggregation; private void initUI() { assert SwingUtilities.isEventDispatchThread(); // --- Results --------------------------------------------------------- locksView = new LockContentionPanel() { protected ProfilerClient getProfilerClient() { return LocksFeatureUI.this.getProfilerClient(); } }; locksView.lockContentionEnabled(); locksView.putClientProperty("HelpCtx.Key", "ProfileLocks.HelpCtx"); // NOI18N // --- Toolbar --------------------------------------------------------- shLabel = new GrayLabel(Bundle.LocksFeatureUI_show()); Action aThreads = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByThreads()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_THREADS); } }; Action aMonitors = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByMonitors()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_MONITORS); } }; shAggregation = new ActionPopupButton(aThreads, aMonitors); shAggregation.setToolTipText(Bundle.LocksFeatureUI_aggregationHint()); toolbar = ProfilerToolbar.create(true); toolbar.addSpace(2); toolbar.addSeparator(); toolbar.addSpace(5); toolbar.add(shLabel); toolbar.addSpace(2); toolbar.add(shAggregation); // --- Sync UI --------------------------------------------------------- setAggregation(LockContentionPanel.Aggregation.BY_THREADS); sessionStateChanged(getSessionState()); } private void refreshToolbar(final int state) { // if (toolbar != null) SwingUtilities.invokeLater(new Runnable() { // public void run() { // } // }); } private void setAggregation(LockContentionPanel.Aggregation aggregation) { locksView.setAggregation(aggregation); shAggregation.selectAction(aggregation.ordinal()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12224 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler/src/org/graalvm/visualvm/lib/profiler/v2/features/LocksFeatureUI.java/#L65-L192 | 2 | 1862 | 12224 | minor |
| 2697 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15320 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2697 | 15320 | major |
| 1255 | {"output": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10491 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 1255 | 10491 | major |
| 1839 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XmiWriterCasConsumer extends CasConsumer_ImplBase { /** * Name of configuration parameter that must be set to the path of a directory into which the * output files will be written. */ public static final String PARAM_OUTPUTDIR = "OutputDirectory"; private File mOutputDir; private int mDocNum; public void initialize() throws ResourceInitializationException { mDocNum = 0; mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * Processes the CAS which was populated by the TextAnalysisEngines. * In this case, the CAS is converted to XMI and written into the output file . * * @param aCAS * a CAS which has been populated by the TAEs * * @throws ResourceProcessException * if there is an error in processing the Resource * * @see org.apache.uima.collection.base_cpm.CasObjectProcessor#processCas(org.apache.uima.cas.CAS) */ public void processCas(CAS aCAS) throws ResourceProcessException { String modelFileName = null; JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // retrieve the filename of the input file from the CAS FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator(); File outFile = null; if (it.hasNext()) { SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next(); File inFile; try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += ".xmi"; outFile = new File(mOutputDir, outFileName); modelFileName = mOutputDir.getAbsolutePath() + "/" + inFile.getName() + ".ecore"; } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xmi"); } // serialize XCAS and write to output file try { writeXmi(jcas.getCas(), outFile, modelFileName); } catch (IOException e) { throw new ResourceProcessException(e); } catch (SAXException e) { throw new ResourceProcessException(e); } } /** * Serialize a CAS to a file in XMI format * * @param aCas * CAS to serialize * @param name * output file * @throws SAXException - * @throws Exception - * * @throws ResourceProcessException - */ private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException { FileOutputStream out = null; try { // write XMI out = new FileOutputStream(name); XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(out, false); ser.serialize(aCas, xmlSer.getContentHandler()); } finally { if (out != null) { out.close(); } } } } |
blob | 1 Long Method | t | f | f | 1. Long Method | blob | 0 | 12146 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-examples/src/main/java/org/apache/uima/examples/xmi/XmiWriterCasConsumer.java/#L48-L148 | 1 | 1839 | 12146 | minor |
| 1794 | YES I found bad smells! The bad smells are: 1) Long method 2) Data Class 3) Long parameter list 4) Primitive Obsession 5) Inconsistent formatting 6) Redundant null check 7) Magic number 8) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
blob | ) Long method2) Data Class3) Long parameter list4) Primitive Obsession5) Inconsistent formatting6) Redundant null check7) Magic number8) Feature envy | t | f | f | ) Long method2) Data Class3) Long parameter list4) Primitive Obsession5) Inconsistent formatting6) Redundant null check7) Magic number8) Feature envy | blob | 0 | 11997 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 1794 | 11997 | minor |
| 2611 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | long method | t | t | f | long method | data class | 0 | 15040 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 2611 | 15040 | minor |
| 2690 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 15292 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 2 | 2690 | 15292 | minor |
| 2470 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 14576 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 2470 | 14576 | critical |
| 1702 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
blob | data class | t | t | f | data class | blob | 0 | 11737 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 1702 | 11737 | major |
| 2060 | YES I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12964 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 2060 | 12964 | major |
| 2214 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13528 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 2214 | 13528 | major |
| 572 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
blob | data class | t | t | f | data class | blob | 0 | 5756 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 572 | 5756 | minor |
| 4881 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13281 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/editor/syntaxcoloring/InternalN4JSParser.java/#L59301-L59322 | 1 | 4881 | 13281 | minor | ||
| 2328 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14146 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 1 | 2328 | 14146 | minor |
| 1740 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface CassandraSieveRepositoryModule { CassandraModule MODULE = CassandraModule.builder() .table(CassandraSieveTable.TABLE_NAME) .comment("Holds SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveTable.USER_NAME, text()) .addClusteringColumn(CassandraSieveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveTable.SCRIPT_CONTENT, text()) .addColumn(CassandraSieveTable.IS_ACTIVE, cboolean()) .addColumn(CassandraSieveTable.SIZE, bigint())) .table(CassandraSieveSpaceTable.TABLE_NAME) .comment("Holds per user current space occupied by SIEVE scripts.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveSpaceTable.USER_NAME, text()) .addColumn(CassandraSieveSpaceTable.SPACE_USED, counter())) .table(CassandraSieveQuotaTable.TABLE_NAME) .comment("Holds per user size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveQuotaTable.USER_NAME, text()) .addColumn(CassandraSieveQuotaTable.QUOTA, bigint())) .table(CassandraSieveClusterQuotaTable.TABLE_NAME) .comment("Holds default size limitations for SIEVE script storage.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveClusterQuotaTable.NAME, text()) .addColumn(CassandraSieveClusterQuotaTable.VALUE, bigint())) .table(CassandraSieveActiveTable.TABLE_NAME) .comment("Denormalisation table. Allows per user direct active SIEVE script retrieval.") .options(options -> options) .statement(statement -> statement .addPartitionKey(CassandraSieveActiveTable.USER_NAME, text()) .addColumn(CassandraSieveActiveTable.SCRIPT_NAME, text()) .addColumn(CassandraSieveActiveTable.DATE, timestamp())) .build(); } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 11840 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-cassandra/src/main/java/org/apache/james/sieve/cassandra/CassandraSieveRepositoryModule.java/#L35-L74 | 1 | 1740 | 11840 | major |
| 531 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 5477 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 531 | 5477 | minor |
| 5458 | {"response":"YES I found bad smells","the bad smells are":["Feature Envy","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 528 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 1 | 5458 | 528 | critical |
| 2375 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | Long Method, 2 Feature Envy"} | t | f | f | . Long Method, 2. Feature Envy"} | blob | 0 | 14315 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 2375 | 14315 | minor |
| 4153 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10936 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 2 | 4153 | 10936 | critical |
| 4432 | {"output": "YES I found bad smells\nthe bad smells are: \n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 11738 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 | 1 | 4432 | 11738 | major |
| 5298 | {"answer":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14828 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 1 | 5298 | 14828 | major |
| 342 | { "error": "You haven't provided any input for me to check for code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Not specified | f | f | f | false | 0 | 3502 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 342 | 3502 | major | |
| 1434 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 10959 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 2 | 1434 | 10959 | major |
| 979 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | long method | t | t | f | long method | blob | 0 | 8840 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 1 | 979 | 8840 | minor |
| 3535 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JcloudsBlobStoreBasedObjectStore implements PersistenceObjectStore { private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStore.class); private final String containerNameFirstPart; private final String containerSubPath; private String locationSpec; private JcloudsLocation location; private BlobStoreContext context; private ManagementContext mgmt; public JcloudsBlobStoreBasedObjectStore(String locationSpec, String containerName) { this.locationSpec = locationSpec; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; } private String[] splitOnce(String path) { String separator = subPathSeparator(); int index = path.indexOf(separator); if (index<0) return new String[] { path, "" }; return new String[] { path.substring(0, index), path.substring(index+separator.length()) }; } public JcloudsBlobStoreBasedObjectStore(JcloudsLocation location, String containerName) { this.location = location; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; getBlobStoreContext(); } public String getSummaryName() { return (locationSpec!=null ? locationSpec : location)+":"+getContainerNameFull(); } public synchronized BlobStoreContext getBlobStoreContext() { if (context==null) { if (location==null) { Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null"); Preconditions.checkNotNull(mgmt, "mgmt not injected / object store not prepared"); location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec); } String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null"); String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null"); String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null"); String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT); context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential); // TODO do we need to get location from region? can't see the jclouds API. // doesn't matter in some places because it's already in the endpoint // String region = location.getConfig(CloudLocationConfig.CLOUD_REGION_ID); context.getBlobStore().createContainerInLocation(null, getContainerNameFirstPart()); } return context; } @Override public void prepareForMasterUse() { // backups not supported here, that is all which is needed for master use // that's now normally done *prior* to calling in to here for writes // (and we have already thrown in prepareForSharedUse if legacy backups have been specified as required) } public String getContainerName() { return getContainerNameFull(); } protected String getContainerNameFull() { return mergePaths(containerNameFirstPart, containerSubPath); } protected String getContainerNameFirstPart() { return containerNameFirstPart; } protected String getItemInContainerSubPath(String path) { if (Strings.isBlank(containerSubPath)) return path; return mergePaths(containerSubPath, path); } @Override public void createSubPath(String subPath) { // not needed - subpaths are created on demant // (and buggy on softlayer w swift w jclouds 1.7.2: // throws a "not found" if we're creating an empty directory from scratch) // context.getBlobStore().createDirectory(getContainerName(), subPath); } protected void checkPrepared() { if (context==null) throw new IllegalStateException("object store not prepared"); } @Override public StoreObjectAccessor newAccessor(String path) { checkPrepared(); return new JcloudsStoreObjectAccessor(context.getBlobStore(), getContainerNameFirstPart(), getItemInContainerSubPath(path)); } protected String mergePaths(String basePath, String ...subPaths) { StringBuilder result = new StringBuilder(basePath); for (String subPath: subPaths) { if (result.length()>0 && subPath.length()>0) { result.append(subPathSeparator()); result.append(subPath); } } return result.toString(); } protected String subPathSeparator() { // in case some object stores don't allow / for paths return "/"; } @Override public List listContentsWithSubPath(final String parentSubPath) { checkPrepared(); return FluentIterable.from(context.getBlobStore().list(getContainerNameFirstPart(), ListContainerOptions.Builder.inDirectory(getItemInContainerSubPath(parentSubPath)))) .transform(new Function() { @Override public String apply(@javax.annotation.Nullable StorageMetadata input) { String result = input.getName(); result = Strings.removeFromStart(result, containerSubPath); result = Strings.removeFromStart(result, "/"); return result; } }).toList(); } @Override public void close() { if (context!=null) context.close(); } @Override public String toString() { return Objects.toStringHelper(this) .add("blobStoreContext", context) .add("basedir", containerNameFirstPart) .toString(); } @Override public void injectManagementContext(ManagementContext mgmt) { if (this.mgmt!=null && !this.mgmt.equals(mgmt)) throw new IllegalStateException("Cannot change mgmt context of "+this); this.mgmt = mgmt; } @SuppressWarnings("deprecation") @Override public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) { if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this); getBlobStoreContext(); if (persistMode==null || persistMode==PersistMode.DISABLED) { log.warn("Should not be using "+this+" when persistMode is "+persistMode); return; } Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED); if (Boolean.TRUE.equals(backups)) { log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location."); throw new FatalConfigurationRuntimeException("Backups not supported for object store ("+this+")"); } } @Override public void deleteCompletely() { if (Strings.isBlank(containerSubPath)) getBlobStoreContext().getBlobStore().deleteContainer(containerNameFirstPart); else newAccessor(containerSubPath).delete(); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 7670 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java/#L52-L237 | 2 | 3535 | 7670 | minor |
| 1261 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10505 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 2 | 1261 | 10505 | minor |
| 186 | { "output": "YES I found bad smells.\nthe bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 2119 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 1 | 186 | 2119 | minor |
| 5766 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14655 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 2 | 5766 | 14655 | major |
| 658 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 6413 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 2 | 658 | 6413 | critical |
| 2449 | { "message": "YES I found bad smells", "detected_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class JobDefinitionLocator extends JobSpecificationVisitor { List jobDefinitions = new ArrayList(); public List getJobDefinitions() { return jobDefinitions; } @Override public Object walk(Object context, Flow sjs) { for (JobNode jobNode : sjs.getSeries()) { walk(context, jobNode); } return context; } @Override public Object walk(Object context, JobDefinition jd) { jobDefinitions.add(jd); return context; } @Override public Object walk(Object context, JobReference jr) { return context; } @Override public Object walk(Object context, Split pjs) { for (JobNode jobNode : pjs.getSeries()) { walk(context, jobNode); } return context; } } |
data class | the bad smells are: long method | t | t | f | the bad smells are: long method | data class | 0 | 14500 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/job/dsl/JobSpecification.java/#L189-L224 | 1 | 2449 | 14500 | minor |
| 2495 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Repetitive code 4. Insufficient modularity 5. Violation of single responsibility principle 6. Inconsistent naming conventions 7. Overly complex code 8. Poor error handling 9. Overriding of unnecessary methods 10. Overuse of static methods and variables. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | Long method2 Feature envy3 Repetitive code 4 Insufficient modularity 5 Violation of single responsibility principle 6 Inconsistent naming conventions 7 Overly complex code 8 Poor error handling 9 Overriding of unnecessary methods | t | f | f | . Long method2. Feature envy3. Repetitive code 4. Insufficient modularity 5. Violation of single responsibility principle 6. Inconsistent naming conventions 7. Overly complex code 8. Poor error handling 9. Overriding of unnecessary methods | blob | 0 | 14640 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2495 | 14640 | minor |
| 1276 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
blob | Long method2Feature envy | t | f | f | .Long method2.Feature envy | blob | 0 | 10587 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 1276 | 10587 | minor |
| 2220 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 2220 | 13551 | major |
| 1500 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeleteIndexAction implements ExpirationAction { private static final Logger logger = LoggerFactory.getLogger(DeleteIndexAction.class); private final PersistentProvenanceRepository repository; private final IndexConfiguration indexConfiguration; private final IndexManager indexManager; public DeleteIndexAction(final PersistentProvenanceRepository repo, final IndexConfiguration indexConfiguration, final IndexManager indexManager) { this.repository = repo; this.indexConfiguration = indexConfiguration; this.indexManager = indexManager; } @Override public File execute(final File expiredFile) throws IOException { // count the number of records and determine the max event id that we are deleting. final long numDeleted = 0; long maxEventId = -1L; try (final RecordReader reader = RecordReaders.newRecordReader(expiredFile, repository.getAllLogFiles(), Integer.MAX_VALUE)) { maxEventId = reader.getMaxEventId(); } catch (final IOException ioe) { logger.warn("Failed to obtain max ID present in journal file {}", expiredFile.getAbsolutePath()); } // remove the records from the index final List indexDirs = indexConfiguration.getIndexDirectories(expiredFile); for (final File indexingDirectory : indexDirs) { final Term term = new Term(FieldNames.STORAGE_FILENAME, LuceneUtil.substringBefore(expiredFile.getName(), ".")); boolean deleteDir = false; final EventIndexWriter writer = indexManager.borrowIndexWriter(indexingDirectory); try { final IndexWriter indexWriter = writer.getIndexWriter(); indexWriter.deleteDocuments(term); indexWriter.commit(); final int docsLeft = indexWriter.numDocs(); deleteDir = docsLeft <= 0; logger.debug("After expiring {}, there are {} docs left for index {}", expiredFile, docsLeft, indexingDirectory); } finally { indexManager.returnIndexWriter(writer); } // we've confirmed that all documents have been removed. Delete the index directory. if (deleteDir) { indexManager.removeIndex(indexingDirectory); indexConfiguration.removeIndexDirectory(indexingDirectory); deleteDirectory(indexingDirectory); logger.info("Removed empty index directory {}", indexingDirectory); } } // Update the minimum index to 1 more than the max Event ID in this file. if (maxEventId > -1L) { indexConfiguration.setMinIdIndexed(maxEventId + 1L); } logger.info("Deleted Indices for Expired Provenance File {} from {} index files; {} documents removed", expiredFile, indexDirs.size(), numDeleted); return expiredFile; } private void deleteDirectory(final File dir) { if (dir == null || !dir.exists()) { return; } final File[] children = dir.listFiles(); if (children == null) { return; } for (final File child : children) { if (child.isDirectory()) { deleteDirectory(child); } else if (!child.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", child.getAbsolutePath()); } } if (!dir.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", dir); } } @Override public boolean hasBeenPerformed(final File expiredFile) throws IOException { return false; } } |
blob | long method | t | t | f | long method | blob | 0 | 11132 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-provenance-repository-bundle/nifi-persistent-provenance-repository/src/main/java/org/apache/nifi/provenance/lucene/DeleteIndexAction.java/#L34-L122 | 1 | 1500 | 11132 | major |
| 4110 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | long method | t | t | f | long method | data class | 0 | 10825 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 1 | 4110 | 10825 | major |
| 3663 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnnotationSubstitutionType extends CustomSubstitutionType { private final String name; public AnnotationSubstitutionType(MetaAccessProvider metaAccess, ResolvedJavaType original) { super(original); assert original.getSuperclass().equals(metaAccess.lookupJavaType(Proxy.class)); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(original); ResolvedJavaType annotationInterfaceType = AnnotationSupport.findAnnotationInterfaceType(original); assert annotationInterfaceType.isAssignableFrom(original); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(annotationInterfaceType); String n = annotationInterfaceType.getName(); assert n.endsWith(";"); name = n.substring(0, n.length() - 1) + "$$ProxyImpl;"; } @Override public String getName() { return name; } @Override public String toString() { return "AnnotationType<" + toJavaName(true) + " -> " + original + ">"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8426 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/annotation/AnnotationSubstitutionType.java/#L33-L61 | 2 | 3663 | 8426 | minor |
| 2482 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14601 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 1 | 2482 | 14601 | minor |
| 200 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "name": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LogTransformer extends Transformer { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public Object transformRow(Map row, Context ctx) { String expr = ctx.getEntityAttribute(LOG_TEMPLATE); String level = ctx.replaceTokens(ctx.getEntityAttribute(LOG_LEVEL)); if (expr == null || level == null) return row; if ("info".equals(level)) { if (log.isInfoEnabled()) log.info(ctx.replaceTokens(expr)); } else if ("trace".equals(level)) { if (log.isTraceEnabled()) log.trace(ctx.replaceTokens(expr)); } else if ("warn".equals(level)) { if (log.isWarnEnabled()) log.warn(ctx.replaceTokens(expr)); } else if ("error".equals(level)) { if (log.isErrorEnabled()) log.error(ctx.replaceTokens(expr)); } else if ("debug".equals(level)) { if (log.isDebugEnabled()) log.debug(ctx.replaceTokens(expr)); } return row; } public static final String LOG_TEMPLATE = "logTemplate"; public static final String LOG_LEVEL = "logLevel"; } |
blob | name: long method | t | t | f | name: long method | blob | 0 | 2244 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/LogTransformer.java/#L35-L67 | 1 | 200 | 2244 | minor |
| 979 | YES I found bad smells the bad smells are: 1. Duplicated code in the functions getRuntime() and getThreadBean() 2. Long method in the function takeThreadDump() 3. Feature envy in the function printThreads() 4. Duplicated code in the functions print16Thread() and print15Thread() 5. Long method in the function printLock() 6. Magic number in the functions printThreads() and printLock() 7. Linear sequence in the function takeHeapDump() 8. Duplicated code in the functions getFlagValue() and setFlagValue() 9. Long method in the function takeHeapHistogram() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | Duplicated code in the functions getRuntime() and getThreadBean() 2 Long method in the function takeThreadDump() 3 Feature envy in the function printThreads() 4 Duplicated code in the functions print | t | f | f | . Duplicated code in the functions getRuntime() and getThreadBean() 2. Long method in the function takeThreadDump() 3. Feature envy in the function printThreads() 4. Duplicated code in the functions print | blob | 0 | 8840 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 2 | 979 | 8840 | minor |
| 4031 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Feature envy 2 Long method | t | f | f | . Feature envy 2. Long method | data class | 0 | 10668 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 2 | 4031 | 10668 | major |
| 255 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class Prefixes { /** * The SI “deca” prefix. This is the only SI prefix encoded on two letters instead than one. * It can be represented by the CJK compatibility character “㍲”, but use of those characters * is generally not recommended outside of Chinese, Japanese or Korean texts. */ private static final String DECA = "da"; /** * The SI prefixes in increasing order. The only two-letters prefix – “da” – is encoded using the JCK compatibility * character “㍲”. The Greek letter μ is repeated twice: the U+00B5 character for micro sign (this is the character * that Apache SIS uses in unit symbols) and the U+03BC character for the Greek small letter “mu” (the later is the * character that appears when decomposing JCK compatibility characters with {@link java.text.Normalizer}). * Both characters have same appearance but different values. * * For each prefix at index i, the multiplication factor is given by 10 raised to power {@code POWERS[i]}. */ private static final char[] PREFIXES = {'E','G','M','P','T','Y','Z','a','c','d','f','h','k','m','n','p','y','z','µ','μ','㍲'}; private static final byte[] POWERS = {18, 9, 6, 15, 12, 24, 21,-18, -2, -1,-15, 2, 3, -3, -9,-12,-24,-21, -6, -6, 1}; /** * The SI prefixes from smallest to largest. Power of tens go from -24 to +24 inclusive with a step of 3, * except for the addition of -2, -1, +1, +2 and the omission of 0. * * @see #symbol(double, int) */ private static final char[] ENUM = {'y','z','a','f','p','n','µ','m','c','d','㍲','h','k','M','G','T','P','E','Z','Y'}; /** * The maximal power of 1000 for the prefixes in the {@link #ENUM} array. Note that 1000⁸ = 1E+24. */ static final int MAX_POWER = 8; /** * The converters for SI prefixes, created when first needed. * * @see #converter(char) */ private static final LinearConverter[] CONVERTERS = new LinearConverter[POWERS.length]; /** * Do not allow instantiation of this class. */ private Prefixes() { } /** * Returns the converter for the given SI prefix, or {@code null} if none. * Those converters are created when first needed and cached for reuse. */ static LinearConverter converter(final char prefix) { final int i = Arrays.binarySearch(PREFIXES, prefix); if (i < 0) { return null; } synchronized (CONVERTERS) { LinearConverter c = CONVERTERS[i]; if (c == null) { final int p = POWERS[i]; final double numerator, denominator; if (p >= 0) { numerator = MathFunctions.pow10(p); denominator = 1; } else { numerator = 1; denominator = MathFunctions.pow10(-p); } c = LinearConverter.scale(numerator, denominator); CONVERTERS[i] = c; } return c; } } /** * Returns the SI prefix symbol for the given scale factor, or 0 if none. * * @param scale the scale factor. * @param power the unit power. For example if we are scaling m², then this is 2. * @return the prefix, or 0 if none. */ static char symbol(double scale, final int power) { switch (power) { case 0: return 0; case 1: break; case 2: scale = Math.sqrt(scale); break; case 3: scale = Math.cbrt(scale); break; default: scale = Math.pow(scale, 1.0/power); } final int n = Numerics.toExp10(Math.getExponent(scale)) + 1; if (AbstractConverter.epsilonEquals(MathFunctions.pow10(n), scale)) { int i = Math.abs(n); switch (i) { case 0: return 0; case 1: // Fallthrough case 2: break; default: { if (i > (MAX_POWER*3) || (i % 3) != 0) { return 0; } i = i/3 + 2; break; } } return ENUM[n >= 0 ? (MAX_POWER+1) + i : (MAX_POWER+2) - i]; } return 0; } /** * Returns the concatenation of the given prefix with the given unit symbol. */ static String concat(final char prefix, final String unit) { return (prefix == '㍲') ? DECA + unit : prefix + unit; } /** * Returns the unit for the given symbol, taking the SI prefix in account. The given string is usually a single symbol * like "km", but may be an expression like "m³" or "m/s" if the given symbol is explicitly registered as an item that * {@link Units#get(String)} recognizes. This method does not perform any arithmetic operation on {@code Unit}, * except a check for the exponent. * * @param uom a symbol compliant with the rules documented in {@link AbstractUnit#symbol}. * @return the unit for the given symbol, or {@code null} if no unit is found. */ static Unit getUnit(final String uom) { Unit unit = Units.get(uom); if (unit == null && uom.length() >= 2) { int s = 1; char prefix = uom.charAt(0); if (prefix == 'd' && uom.charAt(1) == 'a') { prefix = '㍲'; // Converse of above 'concat(char, String)' method. s = 2; // Skip "da", which we represent by '㍲'. } unit = Units.get(uom.substring(s)); if (AbstractUnit.isPrefixable(unit)) { LinearConverter c = Prefixes.converter(prefix); if (c != null) { String symbol = unit.getSymbol(); final int power = ConventionalUnit.power(symbol); if (power != 0) { if (power != 1) { c = LinearConverter.pow(c, power, false); } symbol = Prefixes.concat(prefix, symbol); return new ConventionalUnit<>((AbstractUnit) unit, c, symbol.intern(), (byte) 0, (short) 0); } } } unit = null; } return unit; } /** * If the given system unit should be replaced by pseudo-unit for the purpose of formatting, * returns that pseudo-unit. Otherwise returns {@code null}. This method is for handling the * Special case of {@link Units#KILOGRAM}, to be replaced by {@link Units#GRAM} so a prefix * can be computed. The kilogram may appear in an expression like "kg/m", which we want to * replace by "g/m". We do that by dividing the unit by 1000 (the converter for "milli" prefix). */ @SuppressWarnings("unchecked") static > ConventionalUnit pseudoSystemUnit(final SystemUnit unit) { if ((unit.scope & ~UnitRegistry.SI) == 0 && unit.dimension.numeratorIs('M')) { if (unit == Units.KILOGRAM) { return (ConventionalUnit) Units.GRAM; // Optimization for a common case. } else { String symbol = unit.getSymbol(); if (symbol != null && symbol.length() >= 3 && symbol.startsWith("kg") && !AbstractUnit.isSymbolChar(symbol.codePointAt(2))) { symbol = symbol.substring(1); UnitConverter c = converter('m'); return new ConventionalUnit<>(unit, c, symbol, UnitRegistry.PREFIXABLE, (short) 0).unique(symbol); } } } return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2751 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-utility/src/main/java/org/apache/sis/measure/Prefixes.java/#L37-L216 | 2 | 255 | 2751 | major |
| 687 | {"answer": "YES I found bad smells", "bad smells are": "1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 6633 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 1 | 687 | 6633 | major |
| 1808 | YES I found bad smells. the bad smells are: 1. Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class. 2. Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data. 3. Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class2 Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data3 Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future | t | f | f | . Feature envy: The jsonString() method uses a utility class (JsonUtils) to perform its logic, indicating that it may be better suited as a member of that class rather than in the User class.2. Primitive obsession: The User class uses primitive types (String, int) instead of creating custom objects that encapsulate the data.3. Long parameter list: The constructor for the User class does not have a default empty constructor, and its only constructor has multiple parameters, which may cause maintenance issues as more data needs to be added in the future. | data class | 0 | 12049 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 2 | 1808 | 12049 | minor |
| 698 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Scanner { private final List tokens; private int currentPosition = 0; public Scanner(final List tokens) { this.tokens = tokens; } public NodeSelect scan() { return scanSelect(); } public void checkTail() { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && (item1.getNodeType() != NodeType.OPERATION || item1.getValue().length() != 0)) { currentPosition = num1; throwSyntaxError(SyntaxError.EXPECTING_END_OF_STRING); } } private NodeSelect scanSelect() { final Node node1 = ensureToken(NodeType.NAME, "select", SyntaxError.EXPECTING_SELECT); //$NON-NLS-1$ final NodeSelect select1 = new NodeSelect(); if (scanToken(NodeType.OPERATION, "*") != null) //$NON-NLS-1$ { select1.setFields(null); } else { select1.setFields(scanFieldNameList(false, NodeType.FIELD_LIST)); } while (true) { if (scanToken(NodeType.NAME, "from") != null) //$NON-NLS-1$ { if (select1.getFrom() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_FROM); } select1.setFrom(scanTableName()); continue; } if (scanToken(NodeType.NAME, "where") != null) //$NON-NLS-1$ { if (select1.getWhere() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_WHERE); } select1.setWhere(scanWhere(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getGroupBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_GROUP_BY); } select1.setGroupBy(scanFieldNameList(false, NodeType.GROUP_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "order") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getOrderBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_ORDER_BY); } select1.setOrderBy(scanFieldNameList(true, NodeType.ORDER_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "asof") != null) //$NON-NLS-1$ { if (select1.getAsOf() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_AS_OF); } select1.setAsOf(scanValue(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "mode") != null) //$NON-NLS-1$ { if (select1.getMode() != null) { currentPosition--; throwSyntaxError(SyntaxError.DUPLICATE_MODE); } select1.setMode(ScanMode()); continue; } select1.setStartOffset(node1.getStartOffset()); select1.setEndOffset(((NodeItem) tokens.get(tokens.size() - 1)).getEndOffset()); return select1; } } private Node scanWhere(final NodeTableName table) { return scanCondition4(table); } private Node scanCondition4(final NodeTableName table) { Node node1 = scanCondition3(table); NodeOrOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "or"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "||"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeOrOperator(); operator1.add(node1); } operator1.add(scanCondition3(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition3(final NodeTableName table) { Node node1 = scanCondition2(table); NodeAndOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "and"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "&&"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeAndOperator(); operator1.add(node1); } operator1.add(scanCondition2(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition2(final NodeTableName table) { Node node1 = scanToken(NodeType.NAME, "not"); //$NON-NLS-1$ if (node1 == null) { node1 = scanToken(NodeType.OPERATION, "!"); //$NON-NLS-1$ } if (node1 != null) { final Node node2 = scanCondition2(table); final Node node3 = new NodeNotOperator(node2); node3.setStartOffset(node1.getStartOffset()); node3.setEndOffset(node2.getEndOffset()); return node3; } node1 = scanToken(NodeType.NAME, "ever"); //$NON-NLS-1$ if (node1 != null) { final Node node4 = scanCondition2(table); final Node node5 = new NodeEverOperator(node4); node5.setStartOffset(node1.getStartOffset()); node5.setEndOffset(node4.getEndOffset()); return node5; } node1 = scanToken(NodeType.NAME, "never"); //$NON-NLS-1$ if (node1 != null) { final Node node6 = scanCondition2(table); final Node node7 = new NodeNotOperator(new NodeEverOperator(node6)); node7.setStartOffset(node1.getStartOffset()); node7.setEndOffset(node6.getEndOffset()); return node7; } return scanCondition1(table); } private Node scanCondition1(final NodeTableName table) { final Node node1 = scanToken(NodeType.OPERATION, "("); //$NON-NLS-1$ if (node1 != null) { final Node node2 = scanWhere(table); final Node node3 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ node2.setStartOffset(node1.getStartOffset()); node2.setEndOffset(node3.getEndOffset()); node2.setHasParantheses(true); return node2; } final NodeCondition condition1 = new NodeCondition(); Node node4 = condition1; condition1.setLeft(scanFieldName(table)); final Stack stack1 = new Stack(); while (true) { if (scanToken(NodeType.NAME, "not") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); continue; } if (scanToken(NodeType.NAME, "ever") != null) //$NON-NLS-1$ { stack1.push(NodeType.EVER); continue; } if (scanToken(NodeType.NAME, "never") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); stack1.push(NodeType.EVER); continue; } break; } while (true) { if (stack1.size() <= 0) { condition1.setCondition(scanConditionOperator(node4 != condition1)); if (condition1.getCondition() == Condition.NONE) { throwSyntaxError(SyntaxError.EXPECTING_COMPARISON_OPERATOR); } if (condition1.getCondition() == Condition.GROUP) { condition1.setRight(scanValue(table)); } else if (condition1.getCondition() == Condition.IN) { final Node node5 = ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final Node node6 = scanValueList(table); final Node node7 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ node6.setStartOffset(node5.getStartOffset()); node6.setEndOffset(node7.getEndOffset()); condition1.setRight(node6); } else if (condition1.getCondition() == Condition.UNDER) { condition1.setRight(scanValue(table)); } else { Node node8 = TryScanFieldName(); if (node8 == null) { node8 = TryScanExpression(); } if (node8 != null) { condition1.setRight(node8); } else { throwSyntaxError(SyntaxError.EXPECTING_FIELD_OR_EXPRESSION); } } node4.setStartOffset(condition1.getLeft().getStartOffset()); node4.setEndOffset(condition1.getRight().getEndOffset()); return node4; } final NodeType nodeType = stack1.pop(); if (nodeType == NodeType.NOT) { node4 = new NodeNotOperator(node4); } else if (nodeType == NodeType.EVER) { node4 = new NodeEverOperator(node4); } } } private Node scanValueList(final NodeTableName table) { final NodeValueList list1 = new NodeValueList(); do { list1.add(scanExpression(table)); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ list1.setStartOffset(list1.getItem(0).getStartOffset()); list1.setEndOffset(list1.getItem(list1.getCount() - 1).getEndOffset()); return list1; } private Node scanValue(final NodeTableName table) { final Node node = TryScanSingleValue(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); } return node; } private Node scanExpression(final NodeTableName nodeTable) { final Node node = TryScanExpression(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); return null; } return node; } private Condition scanConditionOperator(final boolean afterNotOrEver) { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && ((item1.getNodeType() == NodeType.NAME) || ((item1.getNodeType() == NodeType.OPERATION) && !afterNotOrEver))) { Condition condition1 = ConditionalOperators.find(item1.getValue()); if (condition1 == Condition.IN && scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { condition1 = Condition.GROUP; } else if (condition1 == Condition.CONTAINS && scanToken(NodeType.NAME, "words") != null) //$NON-NLS-1$ { condition1 = Condition.CONTAINS_WORDS; } if (condition1 != Condition.NONE) { return condition1; } } currentPosition = num1; if (!afterNotOrEver) { return Condition.NONE; } return Condition.EQUALS; } private NodeTableName scanTableName() { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == NodeType.NAME) { return new NodeTableName((NodeName) tokenNode); } currentPosition = savedCurrentPosition; throwSyntaxError(SyntaxError.EXPECTING_TABLE_NAME); return null; } // direction is true if each field name in the field name list can be // suffixed by an optional // direction indicator - asc or desc private NodeFieldList scanFieldNameList(final boolean direction, final NodeType nodeType) { final NodeFieldList fieldListNode = new NodeFieldList(nodeType); while (true) { final NodeFieldName fieldNameNode = scanFieldName(null); if (direction) { if (scanToken(NodeType.NAME, "asc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.ASCENDING); } else if (scanToken(NodeType.NAME, "desc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.DESCENDING); } } fieldListNode.add(fieldNameNode); /* * if the next token is not a comma operator, then the field list is * finished */ if (scanToken(NodeType.OPERATION, ",") == null) //$NON-NLS-1$ { if (fieldListNode.getCount() != 0) { /* * if the field list node is not empty, set it's start and * end offset by using the starting and ending node in the * list */ fieldListNode.setStartOffset(fieldListNode.getItem(0).getStartOffset()); fieldListNode.setEndOffset(fieldListNode.getItem(fieldListNode.getCount() - 1).getEndOffset()); } return fieldListNode; } } } private NodeFieldName scanFieldName(final NodeTableName table) { final Node node = TryScanFieldName(); if (node != null) { return (NodeFieldName) node; } throwSyntaxError(SyntaxError.EXPECTING_FIELD_NAME); return null; } private NodeMode ScanMode() { ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final NodeMode mode = new NodeMode(); do { final int pos = currentPosition; final NodeItem item = nextToken(); if ((item == null) || !(item.getNodeType().equals(NodeType.NAME))) { currentPosition = pos; throwSyntaxError(SyntaxError.EXPECTING_MODE); return null; } mode.add(item); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ mode.setStartOffset(mode.getItem(0).getStartOffset()); mode.setEndOffset(mode.getItem(mode.getCount() - 1).getEndOffset()); return mode; } private NodeItem ensureToken(final NodeType type, final String str, final SyntaxError syntaxError) { final NodeItem tokenNode = scanToken(type, str); if (tokenNode == null) { throwSyntaxError(syntaxError); } return tokenNode; } private void throwSyntaxError(final SyntaxError error) { NodeItem causeNode = null; if (currentPosition < tokens.size()) { causeNode = (NodeItem) tokens.get(currentPosition); } throw new SyntaxException(causeNode, error); } private NodeItem scanToken(final NodeType type, final String str) { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == type && str.equalsIgnoreCase(tokenNode.getValue())) { return tokenNode; } currentPosition = savedCurrentPosition; return null; } private NodeItem nextToken() { if (currentPosition < tokens.size()) { return (NodeItem) tokens.get(currentPosition++); } return null; } private Node TryScanExpression() { int num; Node node = TryScanSingleValue(); if (node == null) { return null; } while (true) { num = currentPosition; final NodeItem item = nextToken(); if (item != null) { Arithmetic none = Arithmetic.NONE; Node node2 = null; if (item.getNodeType() == NodeType.NUMBER) { none = ArithmeticalOperators.find(item.getValue().substring(0, 1)); if (none != Arithmetic.NONE) { item.setValue(item.getValue().substring(1)); node2 = item; } } else if (item.getNodeType() == NodeType.OPERATION) { none = ArithmeticalOperators.find(item.getValue()); if (none != Arithmetic.NONE) { node2 = TryScanSingleValue(); } } if ((none != Arithmetic.NONE) && (node2 != null)) { final NodeArithmetic arithmetic2 = new NodeArithmetic(); arithmetic2.setArithmetic(none); arithmetic2.setLeft(node); arithmetic2.setRight(node2); arithmetic2.setStartOffset(arithmetic2.getLeft().getStartOffset()); arithmetic2.setEndOffset(arithmetic2.getRight().getEndOffset()); node = arithmetic2; continue; } } currentPosition = num; return node; } } private Node TryScanFieldName() { Node node = null; final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (node2.getNodeType() == NodeType.NAME)) { final NodeItem item = scanToken(NodeType.OPERATION, "."); //$NON-NLS-1$ Node node3 = null; if (item != null) { node3 = nextToken(); if ((node3 != null) && (node3.getNodeType() == NodeType.NAME)) { node = new NodeFieldName((NodeName) node2, (NodeName) node3); } } else { node = new NodeFieldName((NodeName) node2); } } if (node == null) { currentPosition = pos; return null; } return node; } private Node TryScanSingleValue() { final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (((node2.getNodeType() == NodeType.NUMBER) || (node2.getNodeType() == NodeType.STRING)) || ((node2.getNodeType() == NodeType.VARIABLE) || (node2.getNodeType() == NodeType.BOOL_VALUE)))) { return node2; } currentPosition = pos; return null; } } |
blob | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | blob | 0 | 6676 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/workitem/internal/wiqlparse/Scanner.java/#L9-L514 | 1 | 698 | 6676 | critical |
| 96 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | long method | t | t | f | long method | blob | 0 | 1275 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 1 | 96 | 1275 | critical |
| 1852 | YES I found bad smells the bad smells: 1. Long method 2. Primitive obsession 3. Feature envy 4. Data class 5. Duplicate code/unnecessary code repetition 6. Type checking using instanceof 7. Inconsistent naming convention for variables 8. Nested if/else statements indicating complex logic 9. Accessing private fields directly rather than through getters/setters 10. Use of raw types instead of generics 11. Lack of encapsulation/data hiding 12. Lack of proper documentation/comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
blob | Long method2 Primitive obsession3 Feature envy4 Data class5 Duplicate code/unnecessary code repetition6 Type checking using instanceof7 Inconsistent naming convention for variables 8 Nested if/else statements indicating complex logic9 Accessing private fields directly rather than through getters/setters | t | f | f | . Long method2. Primitive obsession3. Feature envy4. Data class5. Duplicate code/unnecessary code repetition6. Type checking using instanceof7. Inconsistent naming convention for variables 8. Nested if/else statements indicating complex logic9. Accessing private fields directly rather than through getters/setters | blob | 0 | 12191 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 1852 | 12191 | minor |
| 444 | YES I found bad smells - the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 4319 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 2 | 444 | 4319 | minor |
| 1767 | {"message": "YES I found bad smells", "the bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class OgnlHelper { private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); private OgnlHelper() { } /** * Tests whether or not the given String is a Camel OGNL expression. * * An expression is considered an OGNL expression when it contains either one of the following chars: . or [ * * @param expression the String * @return true if a Camel OGNL expression, otherwise false. */ public static boolean isValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } // the brackets should come in a pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 && bracketEnd > 0) { return bracketBegin == bracketEnd; } return expression.contains("."); } public static boolean isInvalidValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) { return false; } // the brackets should come in pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 || bracketEnd > 0) { return bracketBegin != bracketEnd; } // check for double dots if (expression.contains("..")) { return true; } return false; } /** * Validates whether the method name is using valid java identifiers in the name * Will throw {@link IllegalArgumentException} if the method name is invalid. */ public static void validateMethodName(String method) { if (ObjectHelper.isEmpty(method)) { return; } for (int i = 0; i < method.length(); i++) { char ch = method.charAt(i); if (i == 0 && '.' == ch) { // its a dot before a method name continue; } if (ch == '(' || ch == '[' || ch == '.' || ch == '?') { // break when method name ends and sub method or arguments begin break; } if (i == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method); } } } /** * Tests whether or not the given Camel OGNL expression is using the null safe operator or not. * * @param ognlExpression the Camel OGNL expression * @return true if the null safe operator is used, otherwise false. */ public static boolean isNullSafeOperator(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return false; } return ognlExpression.startsWith("?"); } /** * Removes any leading operators from the Camel OGNL expression. * * Will remove any leading of the following chars: ? or . * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any leading operators. */ public static String removeLeadingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.startsWith("?")) { ognlExpression = ognlExpression.substring(1); } if (ognlExpression.startsWith(".")) { ognlExpression = ognlExpression.substring(1); } return ognlExpression; } /** * Removes any trailing operators from the Camel OGNL expression. * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any trailing operators. */ public static String removeTrailingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.contains("[")) { return StringHelper.before(ognlExpression, "["); } return ognlExpression; } public static String removeOperators(String ognlExpression) { return removeLeadingOperators(removeTrailingOperators(ognlExpression)); } public static KeyValueHolder isOgnlIndex(String ognlExpression) { Matcher matcher = INDEX_PATTERN.matcher(ognlExpression); if (matcher.matches()) { // to avoid empty strings as we want key/value to be null in such cases String key = matcher.group(1); if (ObjectHelper.isEmpty(key)) { key = null; } // to avoid empty strings as we want key/value to be null in such cases String value = matcher.group(2); if (ObjectHelper.isEmpty(value)) { value = null; } return new KeyValueHolder<>(key, value); } return null; } /** * Regular expression with repeating groups is a pain to get right * and then nobody understands the reg exp afterwards. * So we use a bit ugly/low-level Java code to split the OGNL into methods. * * @param ognl the ognl expression * @return a list of methods, will return an empty list, if ognl expression has no methods * @throws IllegalArgumentException if the last method has a missing ending parenthesis */ public static List splitOgnl(String ognl) { List methods = new ArrayList<>(); // return an empty list if ognl is empty if (ObjectHelper.isEmpty(ognl)) { return methods; } StringBuilder sb = new StringBuilder(); int j = 0; // j is used as counter per method boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo] boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo}) for (int i = 0; i < ognl.length(); i++) { char ch = ognl.charAt(i); // special for starting a new method if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?') || (ch != '.' && ch != '?' && ch != ']')) { sb.append(ch); // special if we are doing square bracket if (ch == '[' && !parenthesisBracket) { squareBracket = true; } else if (ch == '(') { parenthesisBracket = true; } else if (ch == ')') { parenthesisBracket = false; } j++; // advance } else { if (ch == '.' && !squareBracket && !parenthesisBracket) { // only treat dot as a method separator if not inside a square bracket block // as dots can be used in key names when accessing maps // a dit denotes end of this method and a new method is to be invoked String s = sb.toString(); // reset sb sb.setLength(0); // pass over ? to the new method if (s.endsWith("?")) { sb.append("?"); s = s.substring(0, s.length() - 1); } // add the method methods.add(s); // reset j to begin a new method j = 0; } else if (ch == ']' && !parenthesisBracket) { // append ending ] to method name sb.append(ch); String s = sb.toString(); // reset sb sb.setLength(0); // add the method methods.add(s); // reset j to begin a new method j = 0; // no more square bracket squareBracket = false; } // and don't lose the char if its not an ] end marker (as we already added that) if (ch != ']' || parenthesisBracket) { sb.append(ch); } // only advance if already begun on the new method if (j > 0) { j++; } } } // add remainder in buffer when reached end of data if (sb.length() > 0) { methods.add(sb.toString()); } String last = methods.isEmpty() ? null : methods.get(methods.size() - 1); if (parenthesisBracket && last != null) { // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis if (last.contains("(") && !last.endsWith(")")) { throw new IllegalArgumentException("Method should end with parenthesis, was " + last); } } return methods; } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 11912 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-util/src/main/java/org/apache/camel/util/OgnlHelper.java/#L27-L292 | 1 | 1767 | 11912 | major |
| 2292 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NsTestPrintStream extends PrintStream { /////////////////////////////////////////////////////////////////////////////////// // // CONSTANTS // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // STATE // /////////////////////////////////////////////////////////////////////////////////// private boolean _chatty; /////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR // /////////////////////////////////////////////////////////////////////////////////// /** Construct a quiet or chatty print stream */ public NsTestPrintStream( PrintStream wrappedStream, boolean chatty ) { super( wrappedStream ); _chatty = chatty; } /////////////////////////////////////////////////////////////////////////////////// // // OVERRIDDEN BEHAVIOR // /////////////////////////////////////////////////////////////////////////////////// public PrintStream append( char c ) { if ( _chatty ) { super.append( c ); } return this; } public PrintStream append( CharSequence csq ) { if ( _chatty ) { super.append( csq ); } return this; } public PrintStream append( CharSequence csq, int start, int end ) { if ( _chatty ) { super.append( csq, start, end ); } return this; } public boolean checkError() { return super.checkError(); } protected void clearError() { super.clearError(); } public void close() { super.close(); } public void flush() { super.flush(); } public void print( boolean b ) { if ( _chatty ) { super.print( b ); } } public void print( char c ) { if ( _chatty ) { super.print( c ); } } public void print( int i ) { if ( _chatty ) { super.print( i ); } } public void print( long l ) { if ( _chatty ) { super.print( l ); } } public void print( float f ) { if ( _chatty ) { super.print( f ); } } public void print( double d ) { if ( _chatty ) { super.print( d ); } } public void print( char[] s ) { if ( _chatty ) { super.print( s ); } } public void print( String s ) { if ( _chatty ) { super.print( s ); } } public void print( Object obj ) { if ( _chatty ) { super.print( obj ); } } public void println() { if ( _chatty ) { super.println(); } } public void println( boolean x ) { if ( _chatty ) { super.println( x ); } } public void println( char x ) { if ( _chatty ) { super.println( x ); } } public void println( int x ) { if ( _chatty ) { super.println( x ); } } public void println( long x ) { if ( _chatty ) { super.println( x ); } } public void println( float x ) { if ( _chatty ) { super.println( x ); } } public void println( double x ) { if ( _chatty ) { super.println( x ); } } public void println( char[] x ) { if ( _chatty ) { super.println( x ); } } public void println( String x ) { if ( _chatty ) { super.println( x ); } } public void println( Object x ) { if ( _chatty ) { super.println( x ); } } public PrintStream printf( String format, Object... args ) { if ( _chatty ) { super.printf( format, args ); } return this; } public PrintStream printf( Locale l, String format, Object... args ) { if ( _chatty ) { super.printf( l, format, args ); } return this; } public PrintStream format( String format, Object... args ) { if ( _chatty ) { super.format( format, args ); } return this; } public PrintStream format( Locale l, String format, Object... args ) { if ( _chatty ) { super.format( l, format, args ); } return this; } public void write( byte[] buf, int off, int len ) { if ( _chatty ) { super.write( buf, off, len ); } } public void write( int b ) { if ( _chatty ) { super.write( b ); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13949 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.tests/org/apache/derbyTesting/system/nstest/NsTestPrintStream.java/#L31-L127 | 1 | 2292 | 13949 | minor |
| 4699 | {"message": "YES I found bad smells", "bad smells are:": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JpaEntityFactoryMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String INDEX_VAR = "index"; private static final JavaSymbolName INDEX_SYMBOL = new JavaSymbolName(INDEX_VAR); private static final JavaSymbolName MAX_SYMBOL = new JavaSymbolName("max"); private static final JavaSymbolName MIN_SYMBOL = new JavaSymbolName("min"); private static final String OBJ_VAR = "obj"; private static final JavaSymbolName OBJ_SYMBOL = new JavaSymbolName(OBJ_VAR); private static final JavaSymbolName VALUE = new JavaSymbolName("value"); private static final JavaSymbolName CREATE_FACTORY_METHOD_NAME = new JavaSymbolName("create"); public static final JavaSymbolName SPECIFIC_METHOD_PREFIX = new JavaSymbolName("getSpecific"); private static final String PROVIDES_TYPE_STRING = JpaEntityFactoryMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); public static String createIdentifier(final JavaType javaType, final LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static String createIdentifier(ClassOrInterfaceTypeDetails details) { final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(details.getDeclaredByMetadataId()); return createIdentifier(details.getType(), logicalPath); } public static JavaType getJavaType(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static LogicalPath getPath(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private JavaType entity; private final List requiredDataOnDemandCollaborators = new ArrayList(); private MethodMetadata randomPersistentEntityMethod; private final Map> embeddedFieldInitializers = new LinkedHashMap>(); private final Map fieldInitializers = new LinkedHashMap(); private EmbeddedIdHolder embeddedIdHolder; private List embeddedHolders; private Map locatedFields; private final MemberDetails entityMemberDetails; /** * Constructor * * @param identifier * @param aspectName * @param governorPhysicalTypeMetadata * @param entity * @param entityMemberDetails * @param locatedFields * @param embeddedHolder * @param entityFactoryClasses * @param embeddedIdHolder */ public JpaEntityFactoryMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JavaType entity, MemberDetails entityMemberDetails, final Map locatedFields, final List embeddedHolders, Set entityFactoryClasses, final EmbeddedIdHolder embeddedIdHolder) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.notNull(locatedFields, "Located fields map required"); Validate.notNull(embeddedHolders, "Embedded holders list required"); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.embeddedIdHolder = embeddedIdHolder; this.embeddedHolders = embeddedHolders; this.locatedFields = locatedFields; builder.addMethod(getCreateMethod()); // Calculate and store field initializers for (final Map.Entry entry : locatedFields.entrySet()) { final FieldMetadata field = entry.getKey(); final String initializer = getFieldInitializer(field, entry.getValue(), entityFactoryClasses); if (!StringUtils.isBlank(initializer)) { this.fieldInitializers.put(field, initializer); } } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { final Map initializers = new LinkedHashMap(); for (final FieldMetadata field : embeddedHolder.getFields()) { initializers.put(field, getFieldInitializer(field, null, entityFactoryClasses)); } this.embeddedFieldInitializers.put(embeddedHolder.getEmbeddedField(), initializers); } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { builder.addMethod(getEmbeddedClassMutatorMethod(embeddedHolder)); addEmbeddedClassFieldMutatorMethodsToBuilder(embeddedHolder, entityFactoryClasses); } for (final MethodMetadataBuilder fieldInitializerMethod : getFieldMutatorMethods()) { builder.addMethod(fieldInitializerMethod); } addCollaboratingFieldsToBuilder(entityFactoryClasses); builder.addMethod(getEmbeddedIdMutatorMethod(entityFactoryClasses)); itdTypeDetails = builder.build(); } private void addCollaboratingFieldsToBuilder( final Set entityFactoryClasses) { final Set fields = new LinkedHashSet(); for (final JavaType entityNeedingCollaborator : this.requiredDataOnDemandCollaborators) { final JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator, entityFactoryClasses); if (collaboratorType != null) { final String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator, entityFactoryClasses) .getSymbolName(); final JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // We really expect the field to be correct if we're going to // rely on it Validate .isTrue(candidate.getFieldType().equals(collaboratorType), "Field '%s' on '%s' must be of type '%s'", collaboratingFieldName, destination.getFullyQualifiedTypeName(), collaboratorType.getFullyQualifiedTypeName()); Validate.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '%s' on '%s' must be private", collaboratingFieldName, destination.getFullyQualifiedTypeName()); Validate.notNull( MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), AUTOWIRED), "Field '%s' on '%s' must be @Autowired", collaboratingFieldName, destination.getFullyQualifiedTypeName()); // It's ok, so we can move onto the new field continue; } // Create field and add it to the ITD, if it hasn't already been if (!fields.contains(fieldSymbolName)) { // Must make the field final List annotations = new ArrayList(); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); builder.addField(new FieldMetadataBuilder(getId(), 0, annotations, fieldSymbolName, collaboratorType)); fields.add(fieldSymbolName); } } } } private void addEmbeddedClassFieldMutatorMethodsToBuilder(final EmbeddedHolder embeddedHolder, final Set dataOnDemandClasses) { final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); final JavaType[] parameterTypes = {embeddedFieldType, JavaType.INT_PRIMITIVE}; final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); for (final FieldMetadata field : embeddedHolder.getFields()) { final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); final JavaSymbolName fieldMutatorMethodName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, fieldMutatorMethodName, false)); final JavaSymbolName embeddedClassMethodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()); if (governorHasMethod(embeddedClassMethodName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } builder.addMethod(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, embeddedClassMethodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType .convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } private String getColumnPrecisionAndScaleBody(final FieldMetadata field, final Map values, final String suffix) { if (values == null || !values.containsKey("precision")) { return InvocableMemberBodyBuilder.getInstance().getOutput(); } final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); Integer precision = (Integer) values.get("precision"); Integer scale = (Integer) values.get("scale"); if (precision != null && scale != null && precision < scale) { scale = 0; } final BigDecimal maxValue; if (scale == null || scale == 0) { maxValue = new BigDecimal(StringUtils.rightPad("9", precision, '9')); } else { maxValue = new BigDecimal(StringUtils.rightPad("9", precision - scale, '9') + "." + StringUtils.rightPad("9", scale, '9')); } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private JavaSymbolName getCollaboratingFieldName(final JavaType entity, final Set dataOnDemandClasses) { JavaSymbolName symbolName = null; JavaType collaboratingType = getCollaboratingType(entity, dataOnDemandClasses); if (collaboratingType != null) { symbolName = new JavaSymbolName(StringUtils.uncapitalize(collaboratingType.getSimpleTypeName())); } return symbolName; } private JavaType getCollaboratingType(final JavaType entity, final Set entityFactoryClasses) { JavaType dataOnDemand = null; for (ClassOrInterfaceTypeDetails dataOnDemandClass : entityFactoryClasses) { String searchDataOnDemand = entity.getSimpleTypeName().concat("DataOnDemand"); if (dataOnDemandClass.getType().getSimpleTypeName().equals(searchDataOnDemand) && governorTypeDetails.getType().getModule() .equals(dataOnDemandClass.getType().getModule())) { dataOnDemand = dataOnDemandClass.getType(); } } return dataOnDemand; } private MethodMetadata getCreateMethod() { // Define methodName final JavaSymbolName methodName = CREATE_FACTORY_METHOD_NAME; List parameterTypes = new ArrayList(); parameterTypes.add(JavaType.INT_PRIMITIVE); // Check if method exists MethodMetadata existingMethod = getGovernorMethod(methodName, parameterTypes); if (existingMethod != null) { return existingMethod; } List parameterNames = new ArrayList(); parameterNames.add(INDEX_SYMBOL); // Add body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); List constructors = entityMemberDetails.getConstructors(); boolean hasDefaultConstructor = false; for (ConstructorMetadata constructor : constructors) { if (constructor.getParameterTypes().isEmpty() && Modifier.isPublic(constructor.getModifier())) { hasDefaultConstructor = true; break; } } if (constructors.isEmpty() || hasDefaultConstructor) { generateDefaultCreateMethodBody(bodyBuilder); } else { generateNoConstructorCreateMethodBody(bodyBuilder); } // Create method MethodMetadataBuilder method = new MethodMetadataBuilder(this.getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); CommentStructure commentStructure = new CommentStructure(); List paramsInfo = new ArrayList(); paramsInfo.add(String.format("%s position of the %s", INDEX_VAR, this.entity.getSimpleTypeName())); JavadocComment comment = new JavadocComment(String.format("Creates a new {@link %s} with the given %s.", this.entity.getSimpleTypeName(), INDEX_VAR), paramsInfo, String.format( "a new transient %s", this.entity.getSimpleTypeName()), null); commentStructure.addComment(comment, CommentLocation.BEGINNING); method.setCommentStructure(commentStructure); return method.build(); } /** * Generate default body for create method * * @param bodyBuilder */ private void generateDefaultCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // Entity obj = new Entity(); bodyBuilder.appendFormalLine("%1$s %2$s = new %1$s();", getNameOfJavaType(this.entity), OBJ_SYMBOL); // Set values for transient object for (final Map.Entry entry : locatedFields.entrySet()) { bodyBuilder.appendFormalLine("%s(%s, %s);", BeanInfoUtils.getMutatorMethodName(entry.getKey()), OBJ_SYMBOL, INDEX_SYMBOL); } // return obj; bodyBuilder.appendFormalLine("return %s;", OBJ_SYMBOL); } /** * Generate body for create method when entity has not default constructor available * * @param bodyBuilder */ private void generateNoConstructorCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // throw new IllegalStateException("No no-argument constructor found for the entity "+ Pet.class.getName() +". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again."); bodyBuilder .appendFormalLine( "throw new IllegalStateException(\"No no-argument constructor found for the entity \"+ %s.class.getName() +\". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again.\");", getNameOfJavaType(this.entity)); } private String getDecimalMinAndDecimalMaxBody(final FieldMetadata field, final AnnotationMetadata decimalMinAnnotation, final AnnotationMetadata decimalMaxAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (decimalMinAnnotation != null && decimalMaxAnnotation == null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation == null && decimalMaxAnnotation != null) { final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation != null && decimalMaxAnnotation != null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue( Double.parseDouble(maxValue) >= Double.parseDouble(minValue), "The value of @DecimalMax must be greater or equal to the value of @DecimalMin for field %s", fieldName); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getDigitsBody(final FieldMetadata field, final AnnotationMetadata digitsAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final Integer integerValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("integer")).getValue(); final Integer fractionValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("fraction")).getValue(); final BigDecimal maxValue = new BigDecimal(StringUtils.rightPad("9", integerValue, '9') + "." + StringUtils.rightPad("9", fractionValue, '9')); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private String getFieldInitializer(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set dataOnDemandClasses) { final JavaType fieldType = field.getFieldType(); final String fieldName = field.getFieldName().getSymbolName(); String initializer = "null"; final String fieldInitializer = field.getFieldInitializer(); final Set fieldCustomDataKeys = field.getCustomData().keySet(); // Date fields included for DataNucleus ( if (fieldType.equals(DATE)) { if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() - 10000000L)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() + 10000000L)"; } else { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); initializer = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime()"; } } else if (fieldType.equals(CALENDAR)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); final String calendarString = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH)"; if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { initializer = calendarString + " - 1)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { initializer = calendarString + " + 1)"; } else { initializer = "Calendar.getInstance()"; } } else if (fieldType.equals(TIMESTAMP)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR, TIMESTAMP); initializer = "new Timestamp(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime().getTime())"; } else if (fieldType.equals(STRING)) { if (fieldInitializer != null && fieldInitializer.contains("\"")) { final int offset = fieldInitializer.indexOf("\""); initializer = fieldInitializer.substring(offset + 1, fieldInitializer.lastIndexOf("\"")); } else { initializer = fieldName; } if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), VALIDATOR_CONSTRAINTS_EMAIL) != null || fieldName.toLowerCase().contains("email")) { initializer = "\"foo\" + " + INDEX_VAR + " + \"@bar.com\""; } else { int maxLength = Integer.MAX_VALUE; // Check for @Size final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null) { final AnnotationAttributeValue maxValue = sizeAnnotation.getAttribute(MAX_SYMBOL); if (maxValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "max", maxValue.getValue()); maxLength = ((Integer) maxValue.getValue()).intValue(); } final AnnotationAttributeValue minValue = sizeAnnotation.getAttribute(MIN_SYMBOL); if (minValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "min", minValue.getValue()); final int minLength = ((Integer) minValue.getValue()).intValue(); Validate.isTrue(maxLength >= minLength, "@Size attribute 'max' must be greater than 'min' for field '%s' in %s", fieldName, entity.getFullyQualifiedTypeName()); if (initializer.length() + 2 < minLength) { initializer = String.format("%1$-" + (minLength - 2) + "s", initializer).replace(' ', 'x'); } } } else { if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map columnValues = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (columnValues.keySet().contains("length")) { final Object lengthValue = columnValues.get("length"); validateNumericAnnotationAttribute(fieldName, "@Column", "length", lengthValue); maxLength = ((Integer) lengthValue).intValue(); } } } switch (maxLength) { case 0: initializer = "\"\""; break; case 1: initializer = "String.valueOf(" + INDEX_VAR + ")"; break; case 2: initializer = "\"" + initializer.charAt(0) + "\" + " + INDEX_VAR; break; default: if (initializer.length() + 2 > maxLength) { initializer = "\"" + initializer.substring(0, maxLength - 2) + "_\" + " + INDEX_VAR; } else { initializer = "\"" + initializer + "_\" + " + INDEX_VAR; } } } } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ \"Y\", \"N\" }"); } else if (fieldType.equals(JavaType.BOOLEAN_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "Boolean.TRUE"); } else if (fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "true"); } else if (fieldType.equals(JavaType.INT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ")"); } else if (fieldType.equals(JavaType.INT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, INDEX_VAR); } else if (fieldType.equals(new JavaType(JavaType.INT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ " + INDEX_VAR + ", " + INDEX_VAR + " }"); } else if (fieldType.equals(JavaType.DOUBLE_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); } else if (fieldType.equals(new JavaType(JavaType.DOUBLE_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").doubleValue(), new Integer(" + INDEX_VAR + ").doubleValue() }"); } else if (fieldType.equals(JavaType.FLOAT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); } else if (fieldType.equals(new JavaType(JavaType.FLOAT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").floatValue(), new Integer(" + INDEX_VAR + ").floatValue() }"); } else if (fieldType.equals(JavaType.LONG_OBJECT)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.LONG_PRIMITIVE)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); } else if (fieldType.equals(new JavaType(JavaType.LONG_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").longValue(), new Integer(" + INDEX_VAR + ").longValue() }"); } else if (fieldType.equals(JavaType.SHORT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.SHORT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); } else if (fieldType.equals(new JavaType(JavaType.SHORT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").shortValue(), new Integer(" + INDEX_VAR + ").shortValue() }"); } else if (fieldType.equals(JavaType.CHAR_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Character('N')"); } else if (fieldType.equals(JavaType.CHAR_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "'N'"); } else if (fieldType.equals(new JavaType(JavaType.CHAR_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ 'Y', 'N' }"); } else if (fieldType.equals(BIG_DECIMAL)) { builder.getImportRegistrationResolver().addImport(BIG_DECIMAL); initializer = BIG_DECIMAL.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(BIG_INTEGER)) { builder.getImportRegistrationResolver().addImport(BIG_INTEGER); initializer = BIG_INTEGER.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(JavaType.BYTE_OBJECT)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ")"; } else if (fieldType.equals(JavaType.BYTE_PRIMITIVE)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ").byteValue()"; } else if (fieldType.equals(JavaType.BYTE_ARRAY_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "String.valueOf(" + INDEX_VAR + ").getBytes()"); } else if (fieldType.equals(entity)) { // Avoid circular references (ROO-562) initializer = OBJ_VAR; } else if (fieldCustomDataKeys.contains(CustomDataKeys.ENUMERATED_FIELD)) { builder.getImportRegistrationResolver().addImport(fieldType); initializer = fieldType.getSimpleTypeName() + ".class.getEnumConstants()[0]"; } else if (collaboratingMetadata != null && collaboratingMetadata.getEntityType() != null) { requiredDataOnDemandCollaborators.add(fieldType); initializer = getFieldInitializerForRelatedEntity(field, collaboratingMetadata, fieldCustomDataKeys, dataOnDemandClasses); } return initializer; } private String getFieldInitializerForRelatedEntity(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set fieldCustomDataKeys, final Set dataOnDemandClasses) { // To avoid circular references, we don't try to set nullable fields final boolean nullableField = field.getAnnotation(NOT_NULL) == null && isNullableJoinColumn(field); if (nullableField) { return null; } JavaSymbolName collaboratingFieldName = getCollaboratingFieldName(field.getFieldType(), dataOnDemandClasses); if (collaboratingFieldName != null) { final String collaboratingName = collaboratingFieldName.getSymbolName(); if (fieldCustomDataKeys.contains(CustomDataKeys.ONE_TO_ONE_FIELD)) { // We try to keep the same ID (ROO-568) return collaboratingName + "." + SPECIFIC_METHOD_PREFIX.getSymbolName() + "(" + INDEX_VAR + ")"; } return collaboratingName + "." + collaboratingMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()"; } else { return null; } } private List getFieldMutatorMethods() { final List fieldMutatorMethods = new ArrayList(); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; for (final Map.Entry entry : fieldInitializers.entrySet()) { final FieldMetadata field = entry.getKey(); final JavaSymbolName mutatorName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); // Locate user-defined method if (governorHasMethod(mutatorName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } // Method not on governor so need to create it final String initializer = entry.getValue(); if (!StringUtils.isBlank(initializer)) { final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, mutatorName, false)); fieldMutatorMethods.add(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, mutatorName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } return fieldMutatorMethods; } private String getFieldValidationBody(final FieldMetadata field, final String initializer, final JavaSymbolName mutatorName, final boolean isFieldOfEmbeddableType) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); String suffix = ""; if (fieldType.equals(JavaType.LONG_OBJECT) || fieldType.equals(JavaType.LONG_PRIMITIVE)) { suffix = "L"; } else if (fieldType.equals(JavaType.FLOAT_OBJECT) || fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { suffix = "F"; } else if (fieldType.equals(JavaType.DOUBLE_OBJECT) || fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { suffix = "D"; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(getTypeStr(fieldType) + " " + fieldName + " = " + initializer + ";"); if (fieldType.equals(JavaType.STRING)) { boolean isUnique = isFieldOfEmbeddableType; @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (!isUnique && values != null && values.containsKey("unique")) { isUnique = (Boolean) values.get("unique"); } // Check for @Size or @Column with length attribute final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null && sizeAnnotation.getAttribute(MAX_SYMBOL) != null) { final Integer maxValue = (Integer) sizeAnnotation.getAttribute(MAX_SYMBOL).getValue(); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + maxValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + maxValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + maxValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (sizeAnnotation == null && values != null) { if (values.containsKey("length")) { final Integer lengthValue = (Integer) values.get("length"); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + lengthValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + lengthValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + lengthValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } else if (JdkJavaType.isDecimalType(fieldType)) { // Check for @Digits, @DecimalMax, @DecimalMin final AnnotationMetadata digitsAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DIGITS); final AnnotationMetadata decimalMinAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MIN); final AnnotationMetadata decimalMaxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MAX); if (digitsAnnotation != null) { bodyBuilder.append(getDigitsBody(field, digitsAnnotation, suffix)); } else if (decimalMinAnnotation != null || decimalMaxAnnotation != null) { bodyBuilder.append(getDecimalMinAndDecimalMaxBody(field, decimalMinAnnotation, decimalMaxAnnotation, suffix)); } else if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); bodyBuilder.append(getColumnPrecisionAndScaleBody(field, values, suffix)); } } else if (JdkJavaType.isIntegerType(fieldType)) { // Check for @Min and @Max bodyBuilder.append(getMinAndMaxBody(field, suffix)); } if (mutatorName != null) { bodyBuilder.appendFormalLine(OBJ_VAR + "." + mutatorName.getSymbolName() + "(" + fieldName + ");"); } return bodyBuilder.getOutput(); } private MethodMetadataBuilder getEmbeddedClassMutatorMethod(final EmbeddedHolder embeddedHolder) { final JavaSymbolName methodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName()); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded class final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedFieldType); bodyBuilder.appendFormalLine(embeddedFieldType.getSimpleTypeName() + " embeddedClass = new " + embeddedFieldType.getSimpleTypeName() + "();"); for (final FieldMetadata field : embeddedHolder.getFields()) { bodyBuilder.appendFormalLine(getEmbeddedFieldMutatorMethodName( embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()).getSymbolName() + "(embeddedClass, " + INDEX_VAR + ");"); } bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedHolder.getEmbeddedMutatorMethodName() + "(embeddedClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private MethodMetadataBuilder getEmbeddedIdMutatorMethod( final Set dataOnDemandClasses) { if (!hasEmbeddedIdentifier()) { return null; } final JavaSymbolName embeddedIdMutator = embeddedIdHolder.getEmbeddedIdMutator(); final JavaSymbolName methodName = getEmbeddedIdMutatorMethodName(); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded id class final JavaType embeddedIdFieldType = embeddedIdHolder.getEmbeddedIdField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedIdFieldType); final StringBuilder sb = new StringBuilder(); final List identifierFields = embeddedIdHolder.getIdFields(); for (int i = 0, n = identifierFields.size(); i < n; i++) { if (i > 0) { sb.append(", "); } final FieldMetadata field = identifierFields.get(i); final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); builder.getImportRegistrationResolver().addImport(fieldType); final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); bodyBuilder.append(getFieldValidationBody(field, initializer, null, true)); sb.append(fieldName); } bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine(embeddedIdFieldType.getSimpleTypeName() + " embeddedIdClass = new " + embeddedIdFieldType.getSimpleTypeName() + "(" + sb.toString() + ");"); bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedIdMutator + "(embeddedIdClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private String getMinAndMaxBody(final FieldMetadata field, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); final AnnotationMetadata minAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN); final AnnotationMetadata maxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX); if (minAnnotation != null && maxAnnotation == null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation == null && maxAnnotation != null) { final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation != null && maxAnnotation != null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue(maxValue.longValue() >= minValue.longValue(), "The value of @Max must be greater or equal to the value of @Min for field %s", fieldName); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getTypeStr(final JavaType fieldType) { builder.getImportRegistrationResolver().addImport(fieldType); final String arrayStr = fieldType.isArray() ? "[]" : ""; String typeStr = fieldType.getSimpleTypeName(); if (fieldType.getFullyQualifiedTypeName().equals( JavaType.FLOAT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "float" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.DOUBLE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "double" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.INT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "int" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.SHORT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "short" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.BYTE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "byte" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.CHAR_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "char" + arrayStr; } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { typeStr = "String[]"; } return typeStr; } private boolean isNullableJoinColumn(final FieldMetadata field) { final AnnotationMetadata joinColumnAnnotation = field.getAnnotation(JOIN_COLUMN); if (joinColumnAnnotation == null) { return true; } final AnnotationAttributeValue nullableAttr = joinColumnAnnotation.getAttribute(new JavaSymbolName("nullable")); return nullableAttr == null || (Boolean) nullableAttr.getValue(); } private void validateNumericAnnotationAttribute(final String fieldName, final String annotationName, final String attributeName, final Object object) { Validate.isTrue(NumberUtils.isNumber(object.toString()), "%s '%s' attribute for field '%s' in backing type %s must be numeric", annotationName, attributeName, fieldName, entity.getFullyQualifiedTypeName()); } public JavaSymbolName getCreateFactoryMethodName() { return JpaEntityFactoryMetadata.CREATE_FACTORY_METHOD_NAME; } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName fieldName) { return BeanInfoUtils.getMutatorMethodName(fieldName); } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName embeddedFieldName, final JavaSymbolName fieldName) { return getEmbeddedFieldMutatorMethodName(new JavaSymbolName(embeddedFieldName.getSymbolName() + StringUtils.capitalize(fieldName.getSymbolName()))); } public List getEmbeddedHolders() { return this.embeddedHolders; } public JavaSymbolName getEmbeddedIdMutatorMethodName() { final List fieldNames = new ArrayList(); for (final FieldMetadata field : fieldInitializers.keySet()) { fieldNames.add(field.getFieldName()); } int index = -1; JavaSymbolName embeddedIdField; while (true) { // Compute the required field name index++; embeddedIdField = new JavaSymbolName("embeddedIdClass" + StringUtils.repeat("_", index)); if (!fieldNames.contains(embeddedIdField)) { // Found a usable name break; } } return BeanInfoUtils.getMutatorMethodName(embeddedIdField); } public JavaType getEntityType() { return this.entity; } /** * Returns the {@link JavaType} representing the physical type of this ITD governor. * * @return the {@link JavaType} for the governor physical type. */ public JavaType getGovernorType() { return this.governorPhysicalTypeMetadata.getType(); } /** * @return the "getRandomEntity():Entity" method (never returns null) */ public MethodMetadata getRandomPersistentEntityMethod() { return randomPersistentEntityMethod; } public boolean hasEmbeddedIdentifier() { return this.embeddedIdHolder != null; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12601 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadata.java/#L77-L1176 | 2 | 4699 | 12601 | critical |
| 5741 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 14081 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5741 | 14081 | minor |
| 508 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 5157 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 1 | 508 | 5157 | minor |
| 2178 | "Yes I found bad smells" The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13410 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 2 | 2178 | 13410 | major |
| 647 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void reset() { RepeatableIteratorWrapper changedIterator = this.changedIterator; if (changedIterator != null) { currentIterator = changedIterator; changedIteratorFieldUpdater.compareAndSet(this, changedIterator, null); } currentIterator.reset(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 6374 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/UpdatableIterator.java/#L58-L66 | 1 | 647 | 6374 | minor |
| 560 | YES I found bad smells the bad smells are: 1. Long method (the entire code is contained in one large method) 2. Feature envy (the boolean observed is not used within this class and seems to belong to another class) 3. Poor naming (errorMsg and setErrorString could be more specific) 4. Duplicate code (the return statement is repeated in two methods) 5. Too much functionality in one class (display() method should not be combined with methods related to error handling) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | Long method (the entire code is contained in one large method)2 Feature envy (the boolean observed is not used within this class and seems to belong to another class)3 Poor naming (errorMsg and setErrorString could be more specific)4 Duplicate code (the return statement is repeated in two methods)5 Too much functionality in one class (display() method should not be combined with methods related to error handling) | t | f | f | . Long method (the entire code is contained in one large method)2. Feature envy (the boolean observed is not used within this class and seems to belong to another class)3. Poor naming (errorMsg and setErrorString could be more specific)4. Duplicate code (the return statement is repeated in two methods)5. Too much functionality in one class (display() method should not be combined with methods related to error handling) | data class | 0 | 5653 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 2 | 560 | 5653 | major |
| 45 | { "message": "YES, I found bad smells", "bad smells are": "1. Long method, 2. Feature envy" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final static class TypeList { Hashtable types; TypeList() { } TypeList(Vector typeNames) { types = new Hashtable(); for ( int i = 0; i < typeNames.size(); i++ ) { String t = ((String) typeNames.elementAt(i)).toLowerCase(); types.put(t, t); } } final boolean contains(String type) { if ( types == null ) { return true; //defaults to all } return types.containsKey(type); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 833 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.traceformat/share/classes/com/ibm/jvm/format/Util.java/#L631-L655 | 2 | 45 | 833 | minor |
| 223 | {"message": "YES I found bad smells", "the identified bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TemporalIntervalStartDatetimeAccessor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; private static final FunctionIdentifier FID = BuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_START_DATETIME; public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new TemporalIntervalStartDatetimeAccessor(); } }; @Override public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IScalarEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IScalarEvaluator createScalarEvaluator(IHyracksTaskContext ctx) throws HyracksDataException { return new IScalarEvaluator() { private final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage(); private final DataOutput out = resultStorage.getDataOutput(); private final IPointable argPtr = new VoidPointable(); private final IScalarEvaluator eval = args[0].createScalarEvaluator(ctx); // possible output @SuppressWarnings("unchecked") private final ISerializerDeserializer datetimeSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADATETIME); private final AMutableDateTime aDateTime = new AMutableDateTime(0); @Override public void evaluate(IFrameTupleReference tuple, IPointable result) throws HyracksDataException { eval.evaluate(tuple, argPtr); byte[] bytes = argPtr.getByteArray(); int startOffset = argPtr.getStartOffset(); resultStorage.reset(); try { if (bytes[startOffset] == ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG) { byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes, startOffset + 1); long startTime = AIntervalSerializerDeserializer.getIntervalStart(bytes, startOffset + 1); if (timeType == ATypeTag.SERIALIZED_DATETIME_TYPE_TAG) { aDateTime.setValue(startTime); datetimeSerde.serialize(aDateTime, out); } else { throw new InvalidDataFormatException(sourceLoc, getIdentifier(), ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } else { throw new TypeMismatchException(sourceLoc, getIdentifier(), 0, bytes[startOffset], ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } catch (IOException e) { throw HyracksDataException.create(e); } result.set(resultStorage); } }; } }; } /* (non-Javadoc) * @see org.apache.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2416 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/accessors/TemporalIntervalStartDatetimeAccessor.java/#L47-L119 | 2 | 223 | 2416 | major |
| 1941 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12485 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 2 | 1941 | 12485 | minor |
| 1857 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | long method | t | t | f | long method | data class | 0 | 12216 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 1857 | 12216 | major |
| 2614 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15045 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 2 | 2614 | 15045 | minor |
| 2896 | {"result": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WordMedian extends Configured implements Tool { private double median = 0; private final static IntWritable ONE = new IntWritable(1); /** * Maps words from line of text into a key-value pair; the length of the word * as the key, and 1 as the value. */ public static class WordMedianMapper extends Mapper { private IntWritable length = new IntWritable(); /** * Emits a key-value pair for counting the word. Outputs are (IntWritable, * IntWritable). * * @param value * This will be a line of text coming in from our input file. */ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { String string = itr.nextToken(); length.set(string.length()); context.write(length, ONE); } } } /** * Performs integer summation of all the values for each key. */ public static class WordMedianReducer extends Reducer { private IntWritable val = new IntWritable(); /** * Sums all the individual values within the iterator and writes them to the * same key. * * @param key * This will be a length of a word that was read. * @param values * This will be an iterator of all the values associated with that * key. */ public void reduce(IntWritable key, Iterable values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } val.set(sum); context.write(key, val); } } /** * This is a standard program to read and find a median value based on a file * of word counts such as: 1 456, 2 132, 3 56... Where the first values are * the word lengths and the following values are the number of times that * words of that length appear. * * @param path * The path to read the HDFS file from (part-r-00000...00001...etc). * @param medianIndex1 * The first length value to look for. * @param medianIndex2 * The second length value to look for (will be the same as the first * if there are an even number of words total). * @throws IOException * If file cannot be found, we throw an exception. * */ private double readAndFindMedian(String path, int medianIndex1, int medianIndex2, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); Path file = new Path(path, "part-r-00000"); if (!fs.exists(file)) throw new IOException("Output not found!"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8)); int num = 0; String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); // grab length String currLen = st.nextToken(); // grab count String lengthFreq = st.nextToken(); int prevNum = num; num += Integer.parseInt(lengthFreq); if (medianIndex2 >= prevNum && medianIndex1 <= num) { System.out.println("The median is: " + currLen); br.close(); return Double.parseDouble(currLen); } else if (medianIndex2 >= prevNum && medianIndex1 < num) { String nextCurrLen = st.nextToken(); double theMedian = (Integer.parseInt(currLen) + Integer .parseInt(nextCurrLen)) / 2.0; System.out.println("The median is: " + theMedian); br.close(); return theMedian; } } } finally { if (br != null) { br.close(); } } // error, no median found return -1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new WordMedian(), args); } @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: wordmedian "); return 0; } setConf(new Configuration()); Configuration conf = getConf(); @SuppressWarnings("deprecation") Job job = new Job(conf, "word median"); job.setJarByClass(WordMedian.class); job.setMapperClass(WordMedianMapper.class); job.setCombinerClass(WordMedianReducer.class); job.setReducerClass(WordMedianReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean result = job.waitForCompletion(true); // Wait for JOB 1 -- get middle value to check for Median long totalWords = job.getCounters() .getGroup(TaskCounter.class.getCanonicalName()) .findCounter("MAP_OUTPUT_RECORDS", "Map output records").getValue(); int medianIndex1 = (int) Math.ceil((totalWords / 2.0)); int medianIndex2 = (int) Math.floor((totalWords / 2.0)); median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf); return (result ? 0 : 1); } public double getMedian() { return median; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2130 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/WordMedian.java/#L43-L212 | 1 | 2896 | 2130 | minor |
| 705 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 6714 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 2 | 705 | 6714 | major |
| 711 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 6777 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 1 | 711 | 6777 | minor |
| 1574 | {"output": "YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | blob | 0 | 11345 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 2 | 1574 | 11345 | critical |
| 2409 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | long method, duplicate code, feature envy | t | t | f | long method, duplicate code, feature envy | blob | 0 | 14391 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 2 | 2409 | 14391 | major |
| 235 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class SequenceTermination extends TimerTask { private long maxInactivityTimeout; void updateInactivityTimeout(long timeout) { maxInactivityTimeout = Math.max(maxInactivityTimeout, timeout); } public void run() { synchronized (DestinationSequence.this) { DestinationSequence.this.scheduledTermination = null; RMEndpoint rme = destination.getReliableEndpoint(); long lat = Math.max(rme.getLastControlMessage(), rme.getLastApplicationMessage()); if (0 == lat) { return; } long now = System.currentTimeMillis(); if (now - lat >= maxInactivityTimeout) { // terminate regardless outstanding acknowledgments - as we assume that the client is // gone there is no point in sending a SequenceAcknowledgment LogUtils.log(LOG, Level.WARNING, "TERMINATING_INACTIVE_SEQ_MSG", DestinationSequence.this.getIdentifier().getValue()); DestinationSequence.this.destination.terminateSequence(DestinationSequence.this, true); Source source = rme.getSource(); if (source != null) { SourceSequence ss = source.getAssociatedSequence(DestinationSequence.this.getIdentifier()); if (ss != null) { source.removeSequence(ss); } } } else { // reschedule SequenceTermination st = new SequenceTermination(); st.updateInactivityTimeout(maxInactivityTimeout); DestinationSequence.this.destination.getManager().getTimer() .schedule(st, maxInactivityTimeout); } } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2555 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/rm/src/main/java/org/apache/cxf/ws/rm/DestinationSequence.java/#L565-L605 | 2 | 235 | 2555 | minor |
| 607 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 6104 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 607 | 6104 | major |
| 2019 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method, 3.Magic number, 4.Duplicate code, 5.Inconsistent formatting, 6.Unnecessary constructors, 7.Unformatted comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Feature envy, 2Long method, 3Magic number, 4Duplicate code, 5Inconsistent formatting, 6Unnecessary constructors, 7Unformatted comments | t | f | f | .Feature envy, 2.Long method, 3.Magic number, 4.Duplicate code, 5.Inconsistent formatting, 6.Unnecessary constructors, 7.Unformatted comments | data class | 0 | 12781 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 2019 | 12781 | major |
| 2051 | YES I found bad smells The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 12894 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 2 | 2051 | 12894 | major |
| 269 | {"response": "YES I found bad smells", "the bad smells are": [ "1. Long method" ]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2890 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 269 | 2890 | minor |
| 291 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 3076 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 291 | 3076 | critical |
| 2160 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13321 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 2160 | 13321 | major |
| 587 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Context getContinuationContext(Name n) throws NamingException { Object obj = lookup(n.get(0)); CannotProceedException cpe = new CannotProceedException(); cpe.setResolvedObj(obj); cpe.setEnvironment(myEnv); return NamingManager.getContinuationContext(cpe); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 5854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java/#L195-L201 | 1 | 587 | 5854 | minor |
| 2642 | { private int[][] data; public ArrayImageSource( int width, int height ) { super( width, height ); data = new int[width][height]; } public void setPixelRGB(int x, int y, int rgb) { data[x][y] = rgb; } Th "Yes I found bad smells. The bad smells are: 1. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | Feature Envy | t | f | f | . Feature Envy | data class | 0 | 15145 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 2642 | 15145 | major |
| 2323 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14132 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 2323 | 14132 | minor |
| 2057 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12952 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 2 | 2057 | 12952 | major |
| 902 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method 3. Feature envy 4. Primitive obsession 5. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @NodeInfo(cycles = CYCLES_2, size = SIZE_1) public final class BitScanForwardNode extends UnaryNode implements ArithmeticLIRLowerable { public static final NodeClass TYPE = NodeClass.create(BitScanForwardNode.class); public BitScanForwardNode(ValueNode value) { super(TYPE, StampFactory.forInteger(JavaKind.Int, 0, ((PrimitiveStamp) value.stamp(NodeView.DEFAULT)).getBits()), value); assert value.getStackKind() == JavaKind.Int || value.getStackKind() == JavaKind.Long; } @Override public Stamp foldStamp(Stamp newStamp) { assert newStamp.isCompatible(getValue().stamp(NodeView.DEFAULT)); IntegerStamp valueStamp = (IntegerStamp) newStamp; int min; int max; long mask = CodeUtil.mask(valueStamp.getBits()); int firstAlwaysSetBit = scan(valueStamp.downMask() & mask); int firstMaybeSetBit = scan(valueStamp.upMask() & mask); if (firstAlwaysSetBit == -1) { int lastMaybeSetBit = BitScanReverseNode.scan(valueStamp.upMask() & mask); min = firstMaybeSetBit; max = lastMaybeSetBit; } else { min = firstMaybeSetBit; max = firstAlwaysSetBit; } return StampFactory.forInteger(JavaKind.Int, min, max); } public static ValueNode tryFold(ValueNode value) { if (value.isConstant()) { JavaConstant c = value.asJavaConstant(); if (c.asLong() != 0) { return ConstantNode.forInt(value.getStackKind() == JavaKind.Int ? scan(c.asInt()) : scan(c.asLong())); } } return null; } @Override public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) { ValueNode folded = tryFold(forValue); return folded != null ? folded : this; } /** * Utility method with defined return value for 0. * * @param v * @return number of trailing zeros or -1 if {@code v} == 0. */ public static int scan(long v) { if (v == 0) { return -1; } return Long.numberOfTrailingZeros(v); } /** * Utility method with defined return value for 0. * * @param v * @return number of trailing zeros or -1 if {@code v} == 0. */ public static int scan(int v) { return scan(0xffffffffL & v); } /** * Raw intrinsic for bsf instruction. * * @param v * @return number of trailing zeros or an undefined value if {@code v} == 0. */ @NodeIntrinsic public static native int unsafeScan(long v); /** * Raw intrinsic for bsf instruction. * * @param v * @return number of trailing zeros or an undefined value if {@code v} == 0. */ @NodeIntrinsic public static native int unsafeScan(int v); @Override public void generate(NodeLIRBuilderTool builder, ArithmeticLIRGeneratorTool gen) { builder.setResult(this, gen.emitBitScanForward(builder.operand(getValue()))); } } |
blob | Magic numbers2 Long method3 Feature envy4 Primitive obsession5 Lack of comments/documentation | t | f | f | . Magic numbers2. Long method3. Feature envy4. Primitive obsession5. Lack of comments/documentation | blob | 0 | 8167 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/BitScanForwardNode.java/#L53-L144 | 2 | 902 | 8167 | minor |
| 2568 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14874 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 | 1 | 2568 | 14874 | minor |
| 1201 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10284 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 2 | 1201 | 10284 | critical |
| 991 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9033 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 2 | 991 | 9033 | minor |
| 595 | YES I found bad smells. The bad smells are: 1. Long method (Contains multiple methods with similar functionality) 2. Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Exceptions { private Exceptions() { } public static IllegalArgumentException propertyKeyCanNotBeEmpty() { return new IllegalArgumentException("Property key can not be the empty string"); } public static IllegalArgumentException propertyKeyCanNotBeNull() { return new IllegalArgumentException("Property key can not be null"); } public static IllegalArgumentException propertyValueCanNotBeNull() { return new IllegalArgumentException("Property value can not be null"); } public static IllegalArgumentException propertyKeyCanNotBeAHiddenKey(final String key) { return new IllegalArgumentException("Property key can not be a hidden key: " + key); } public static IllegalStateException propertyDoesNotExist() { return new IllegalStateException("The property does not exist as it has no key, value, or associated element"); } public static IllegalStateException propertyDoesNotExist(final Element element, final String key) { return new IllegalStateException("The property does not exist as the key has no associated value for the provided element: " + element + ":" + key); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val) { return dataTypeOfPropertyValueNotSupported(val, null); } public static IllegalArgumentException dataTypeOfPropertyValueNotSupported(final Object val, final Exception rootCause) { return new IllegalArgumentException(String.format("Property value [%s] is of type %s is not supported", val, val.getClass()), rootCause); } public static IllegalStateException propertyRemovalNotSupported() { return new IllegalStateException("Property removal is not supported"); } } |
data class | Long method (Contains multiple methods with similar functionality)2 Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | t | f | f | . Long method (Contains multiple methods with similar functionality)2. Feature envy (Methods primarily accessing and/or modifying properties of a different class instead of their own) | data class | 0 | 5930 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Property.java/#L129-L169 | 2 | 595 | 5930 | major |
| 412 | YES I found bad smells the bad smells are: 1. Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes. This indicates that the class may have a high level of dependency on other classes and may not be cohesive. 2. Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods. 3. Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication. 4. Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose. 5. Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes. Encapsulation could improve data integrity. 6. Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types. This violates the open-closed principle. 7. Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes This indicates that the class may have a high level of dependency on other classes and may not be cohesive2 Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods3 Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication4 Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose5 Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes Encapsulation could improve data integrity6 Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types This violates the open-closed principle7 Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set | t | f | f | . Feature envy: The DynRealmMembership class contains methods and properties that primarily operate on and belong to the JPADynRealm and JPAAnyType classes. This indicates that the class may have a high level of dependency on other classes and may not be cohesive.2. Long method: The class contains several getter and setter methods which are relatively short, but the overall length of the class may be considered long and may benefit from refactoring into smaller, more focused methods.3. Duplicated code: The checkType() method is repeated in both the setDynRealm() and setAnyType() methods, indicating potential code duplication.4. Inappropriate naming: The name FIQLCond for the fiql property may not be clear or descriptive enough for other developers to understand its purpose.5. Lack of encapsulation: The dynRealm, anyType, and fiql properties are all public, allowing direct access and modification by other classes. Encapsulation could improve data integrity.6. Violation of OCP: The DynRealmMembership class is directly referencing and type-casting the JPADynRealm and JPAAnyType classes, which limits the flexibility to extend or add new types. This violates the open-closed principle.7. Lack of validation: The setFIQLCond() method does not validate the input before setting the fiql property, potentially allowing invalid values to be set. | data class | 0 | 4215 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 412 | 4215 | critical |
| 1711 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 11768 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 1711 | 11768 | minor |
| 61 | { "response": { "message": "YES, I found bad smells", "bad_smells": { "1. Long method": "The readNullTerminatedString method is quite lengthy.", "2. Feature envy": "The method seems to be more concerned with data fields than its own scope." } } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } |
long method | Not specified | f | f | f | false | 0 | 1020 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L473-L485 | 2 | 61 | 1020 | minor | |
| 877 | YES I found one bad smells. The bad smells are: 1. Long class 2. Shotgun Surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
blob | Long class2 Shotgun Surgery | t | f | f | . Long class2. Shotgun Surgery | blob | 0 | 8011 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 877 | 8011 | minor |
| 1545 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Long class 5. Complex class 6. Inappropriate naming convention 7. Nested class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JpegRewriter extends BinaryFileParser { private static final ByteOrder JPEG_BYTE_ORDER = ByteOrder.BIG_ENDIAN; private static final SegmentFilter EXIF_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isExifSegment(); } }; private static final SegmentFilter XMP_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isXmpSegment(); } }; private static final SegmentFilter PHOTOSHOP_APP13_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isPhotoshopApp13Segment(); } }; /** * Constructor. to guess whether a file contains an image based on its file * extension. */ public JpegRewriter() { setByteOrder(JPEG_BYTE_ORDER); } protected static class JFIFPieces { public final List pieces; public final List segmentPieces; public JFIFPieces(final List pieces, final List segmentPieces) { this.pieces = pieces; this.segmentPieces = segmentPieces; } } protected abstract static class JFIFPiece { protected abstract void write(OutputStream os) throws IOException; @Override public String toString() { return "[" + this.getClass().getName() + "]"; } } protected static class JFIFPieceSegment extends JFIFPiece { public final int marker; private final byte[] markerBytes; private final byte[] segmentLengthBytes; private final byte[] segmentData; public JFIFPieceSegment(final int marker, final byte[] segmentData) { this(marker, ByteConversions.toBytes((short) marker, JPEG_BYTE_ORDER), ByteConversions.toBytes((short) (segmentData.length + 2), JPEG_BYTE_ORDER), segmentData); } JFIFPieceSegment(final int marker, final byte[] markerBytes, final byte[] segmentLengthBytes, final byte[] segmentData) { this.marker = marker; this.markerBytes = markerBytes; this.segmentLengthBytes = segmentLengthBytes; this.segmentData = segmentData; // TODO clone? } @Override public String toString() { return "[" + this.getClass().getName() + " (0x" + Integer.toHexString(marker) + ")]"; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(segmentLengthBytes); os.write(segmentData); } public boolean isApp1Segment() { return marker == JpegConstants.JPEG_APP1_MARKER; } public boolean isAppSegment() { return marker >= JpegConstants.JPEG_APP0_MARKER && marker <= JpegConstants.JPEG_APP15_MARKER; } public boolean isExifSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.EXIF_IDENTIFIER_CODE)) { return false; } return true; } public boolean isPhotoshopApp13Segment() { if (marker != JpegConstants.JPEG_APP13_MARKER) { return false; } if (!new IptcParser().isPhotoshopJpegSegment(segmentData)) { return false; } return true; } public boolean isXmpSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.XMP_IDENTIFIER)) { return false; } return true; } public byte[] getSegmentData() { return segmentData; // TODO clone? } } static class JFIFPieceImageData extends JFIFPiece { private final byte[] markerBytes; private final byte[] imageData; JFIFPieceImageData(final byte[] markerBytes, final byte[] imageData) { super(); this.markerBytes = markerBytes; this.imageData = imageData; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(imageData); } } protected JFIFPieces analyzeJFIF(final ByteSource byteSource) throws ImageReadException, IOException { final List pieces = new ArrayList<>(); final List segmentPieces = new ArrayList<>(); final JpegUtils.Visitor visitor = new JpegUtils.Visitor() { // return false to exit before reading image data. @Override public boolean beginSOS() { return true; } @Override public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) { pieces.add(new JFIFPieceImageData(markerBytes, imageData)); } // return false to exit traversal. @Override public boolean visitSegment(final int marker, final byte[] markerBytes, final int segmentLength, final byte[] segmentLengthBytes, final byte[] segmentData) throws ImageReadException, IOException { final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); pieces.add(piece); segmentPieces.add(piece); return true; } }; new JpegUtils().traverseJFIF(byteSource, visitor); return new JFIFPieces(pieces, segmentPieces); } private interface SegmentFilter { boolean filter(JFIFPieceSegment segment); } protected List removeXmpSegments(final List segments) { return filterSegments(segments, XMP_SEGMENT_FILTER); } protected List removePhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER); } protected List findPhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER, true); } protected List removeExifSegments(final List segments) { return filterSegments(segments, EXIF_SEGMENT_FILTER); } protected List filterSegments(final List segments, final SegmentFilter filter) { return filterSegments(segments, filter, false); } protected List filterSegments(final List segments, final SegmentFilter filter, final boolean reverse) { final List result = new ArrayList<>(); for (final T piece : segments) { if (piece instanceof JFIFPieceSegment) { if (filter.filter((JFIFPieceSegment) piece) ^ !reverse) { result.add(piece); } } else if (!reverse) { result.add(piece); } } return result; } protected List insertBeforeFirstAppSegments( final List segments, final List newSegments) throws ImageWriteException { int firstAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { if (firstAppIndex == -1) { firstAppIndex = i; } } } final List result = new ArrayList(segments); if (firstAppIndex == -1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(firstAppIndex, newSegments); return result; } protected List insertAfterLastAppSegments( final List segments, final List newSegments) throws ImageWriteException { int lastAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { lastAppIndex = i; } } final List result = new ArrayList(segments); if (lastAppIndex == -1) { if (segments.size() < 1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(1, newSegments); } else { result.addAll(lastAppIndex + 1, newSegments); } return result; } protected void writeSegments(final OutputStream outputStream, final List segments) throws IOException { try (DataOutputStream os = new DataOutputStream(outputStream)) { JpegConstants.SOI.writeTo(os); for (final JFIFPiece piece : segments) { piece.write(os); } } } // private void writeSegment(OutputStream os, JFIFPieceSegment piece) // throws ImageWriteException, IOException // { // byte markerBytes[] = convertShortToByteArray(JPEG_APP1_MARKER, // JPEG_BYTE_ORDER); // if (piece.segmentData.length > 0xffff) // throw new JpegSegmentOverflowException("Jpeg segment is too long: " // + piece.segmentData.length); // int segmentLength = piece.segmentData.length + 2; // byte segmentLengthBytes[] = convertShortToByteArray(segmentLength, // JPEG_BYTE_ORDER); // // os.write(markerBytes); // os.write(segmentLengthBytes); // os.write(piece.segmentData); // } public static class JpegSegmentOverflowException extends ImageWriteException { private static final long serialVersionUID = -1062145751550646846L; public JpegSegmentOverflowException(final String message) { super(message); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Long class5 Complex class6 Inappropriate naming convention7 Nested class | t | f | f | . Long method2. Feature envy3. Duplicate code4. Long class5. Complex class6. Inappropriate naming convention7. Nested class | blob | 0 | 11250 | https://github.com/apache/commons-imaging/blob/fa7c16f434061d441d1c0d9dbcfd0f4c3092c880/src/main/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegRewriter.java/#L40-L353 | 2 | 1545 | 11250 | major |
| 337 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicated code 3. Inconsistent spacing and indentation 4. Unused imports 5. Unused variables 6. Magic numbers/constants without explanation 7. Use of raw types without type argument 8. Missing comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long method2 Duplicated code3 Inconsistent spacing and indentation4 Unused imports5 Unused variables6 Magic numbers/constants without explanation7 Use of raw types without type argument8 Missing comments/documentation | t | f | f | . Long method2. Duplicated code3. Inconsistent spacing and indentation4. Unused imports5. Unused variables6. Magic numbers/constants without explanation7. Use of raw types without type argument8. Missing comments/documentation | data class | 0 | 3472 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 337 | 3472 | major |
| 1574 | {"response":"YES I found bad smells","the bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMatrix { // columns (index 0) final static String[] COLS = { "owned", "inherited", "implemented" }; final static int OWNED = 0; final static int INHERITED = 1; final static int IMPLEMENTED = 2; final static int CONSUMED = 3; /** Number of source kinds, *not* including {@link #CONSUMED}. */ final static int SOURCE_COUNT_WITHOUT_CONSUMED = 3; // number of columns (not considering CONSUMED) final static int MEMBER_TYPE_COUNT = MemberType.values().length; // number of rows /** * Set of actually consumed members, added in via {@link #markConsumed(MemberList)}. */ private final Set consumed; // rows (index 1) according to MemberType values private final MemberList[][] memberMatrix; /** * List of members from interfaces that are not implemented, because they are static. */ private final MemberList nonImplemented; /** * Iterator which holds information about the source (owned, consumed, inherited, implemented) of the last returned * element. */ public class SourceAwareIterator implements Iterator { private int lastRetrievedSource = -1; private TMember lastRetrievedElement; /** The source used to find the next element */ protected int source; /** The current iterator */ protected Iterator currentIter; private TMember next; final private boolean returnConsumed; SourceAwareIterator(boolean returnConsumed) { this.returnConsumed = returnConsumed; initIter(); next = findNext(); } /** * Initialized iterator with which we start, the owned members by default. */ protected void initIter() { source = OWNED; currentIter = members(source).iterator(); } /** * Returns true if the last returned member is actually contained in the type, that is it is either owned, * inherited, or mixed in. If it is inherited, it is not overridden. */ public boolean isActualMember() { return lastRetrievedSource == OWNED || lastRetrievedSource == CONSUMED || (lastRetrievedSource == INHERITED && isActuallyInherited(lastRetrievedElement)); } /** * Returns true if the source of the last returned element is an interface (either consumed in classifier or to * be implemented). */ public boolean isInterfaceMember() { return lastRetrievedSource == IMPLEMENTED; } /** * Returns true if the source of the last returned element is the super class. */ public boolean isInheritedMember() { return lastRetrievedSource == INHERITED; } /** * Returns true if the source of the last returned element is the class itself. */ public boolean isOwnedMember() { return lastRetrievedSource == OWNED; } /** * Finds next member. */ protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (!returnConsumed || source != IMPLEMENTED || !consumed.contains(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } /** * Selects the next iterator. */ protected Iterator nextIter() { switch (source) { case OWNED: if (returnConsumed) { source = CONSUMED; return consumed.iterator(); } // else // $FALL-THROUGH$ case CONSUMED: { source = INHERITED; return members(source).iterator(); } case INHERITED: { source = IMPLEMENTED; return members(source).iterator(); } case IMPLEMENTED: // $FALL-THROUGH$ default: source = -1; return null; } } @Override public boolean hasNext() { return source >= 0; } @Override public TMember next() { if (!hasNext()) { throw new NoSuchElementException(); } lastRetrievedElement = next; lastRetrievedSource = source; next = findNext(); return lastRetrievedElement; } } /** * Iterator that iterates only over consumed and actually inherited members. */ public class ActuallyInheritedAndConsumedMembersIterator extends SourceAwareIterator { /** Delegates to super constructor */ ActuallyInheritedAndConsumedMembersIterator() { super(true); } @Override protected void initIter() { source = CONSUMED; currentIter = consumed.iterator(); } @Override protected TMember findNext() { do { while (currentIter.hasNext()) { TMember m = currentIter.next(); if (source == CONSUMED || isActuallyInherited(m)) { return m; } } currentIter = nextIter(); } while (source >= 0); return null; } @Override protected Iterator nextIter() { switch (source) { case CONSUMED: { source = INHERITED; return members(source).iterator(); } default: source = -1; return null; } } } /** * Creates an empty matrix. */ @SuppressWarnings("unchecked") public MemberMatrix() { memberMatrix = new MemberList[SOURCE_COUNT_WITHOUT_CONSUMED][MEMBER_TYPE_COUNT]; consumed = new HashSet<>(2); nonImplemented = new MemberList<>(2); } /** * @see N4JSMemberRedefinitionValidator#constraints_61_Consumption(MemberMatrix) */ @SuppressWarnings("javadoc") public void markConsumed(MemberList consumedMembers) { consumed.addAll(consumedMembers); } /** * Tells if the given member is one of the "consumed members" added via method {@link #markConsumed(MemberList)}. */ public boolean isConsumed(TMember member) { return consumed.contains(member); } /** * Returns true if the matrix contains an owned getter and an owned setter. */ public boolean hasOwnedAccessorPair() { return !members(OWNED, GETTER).isEmpty() && !members(OWNED, SETTER).isEmpty(); } /** * Returns true if the matrix contains a mixed accessor pair. That is that getter and setter have different origins * (inherited, owned). This method doesn't consider consumed members. */ public boolean hasMixedAccessorPair() { boolean hasOwnedGetter = !members(OWNED, GETTER).isEmpty(); boolean hasOwnedSetter = !members(OWNED, SETTER).isEmpty(); boolean hasInheritedGetter = !members(INHERITED, GETTER).isEmpty(); boolean hasInheritedSetter = !members(INHERITED, SETTER).isEmpty(); return (!hasOwnedGetter && hasInheritedGetter && hasOwnedSetter) || (hasOwnedGetter && hasInheritedSetter && !hasOwnedSetter); } /** * Returns {@code true} if the matrix contains a getter as well as a setter. */ public boolean hasAccessorPair() { return (!members(OWNED, GETTER).isEmpty() || !members(INHERITED, GETTER).isEmpty() || !members(IMPLEMENTED, GETTER).isEmpty()) && (!members(OWNED, SETTER).isEmpty() || !members(INHERITED, SETTER).isEmpty() || !members(IMPLEMENTED, SETTER).isEmpty()); } /** * Returns all owned, inherited and implemented members (but not consumed members, since they are already contained * in "implemented"). */ public SourceAwareIterator allMembers() { return new SourceAwareIterator(false); } /** * Returns all actually inherited and actually consumed in members. The latter requires them to be set before. Owned * members are always actual members (and usually handled elsewhere by caller). */ public ActuallyInheritedAndConsumedMembersIterator actuallyInheritedAndMixedMembers() { return new ActuallyInheritedAndConsumedMembersIterator(); } /** * Returns a source aware iterator, with the elements are ordered according to owned, consumed, inherited, and * implemented. Consumed members are only returned once. */ public SourceAwareIterator ownedConsumedInheritedImplemented() { return new SourceAwareIterator(true); } private MemberList members(int source, MemberType type) { @SuppressWarnings("unchecked") MemberList list = (MemberList) memberMatrix[source][type.getValue()]; if (list == null) { return MemberList.emptyList(); } return list; } private boolean hasOwnedOrNotAbstractMember(int source, MemberType type) { MemberList list = members(source, type); if (list.isEmpty()) { return false; } if (source == OWNED) { return true; } return list.stream().anyMatch(m -> !m.isAbstract()); } /** * Returns all owned members, which could be multiple members in case of accessors or in error cases. */ public Iterable owned() { return members(OWNED); } /** * Returns all inherited members, which could be multiple members in case of accessors or in error cases. */ public Iterable inherited() { return members(INHERITED); } /** * Returns all implemented members, which could be multiple members in case of accessors, if several interfaces * provide the same member, or in error cases. */ public Iterable implemented() { return members(IMPLEMENTED); } private Iterable members(int source) { return hasSource(source) ? Iterables.concat(members( source, GETTER), members(source, SETTER), members(source, FIELD), members(source, METHOD)) : MemberList.emptyList(); } /** * Returns the "non-implemented" members, i.e. static members from interfaces which are ignored in the matrix, * because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for details. */ public Iterable nonImplemented() { return nonImplemented; } /** * Returns true if the matrix contains owned members. */ public boolean hasOwned() { return hasSource(OWNED); } /** * Returns true if the matrix contains inherited members. */ public boolean hasInherited() { return hasSource(INHERITED); } /** * Returns true if the matrix contains implemented members. */ public boolean hasImplemented() { return hasSource(IMPLEMENTED); } /** * Returns true iff there were "non-implemented" members, i.e. static members from interfaces which are ignored in * the matrix, because there is no inheritance for static members of interfaces. See {@link #add(int, TMember)} for * details. */ public boolean hasNonImplemented() { return !nonImplemented.isEmpty(); } private boolean hasSource(int source) { for (int i = 0; i < MEMBER_TYPE_COUNT; i++) { if (memberMatrix[source][i] != null) { return true; } } return false; } /** * Returns true if the given member stemming from the super class (not checked here) is actually inherited and not * overridden by owned or consumed members. In case of meta-type problems, the inherited member is not actually * inherited. Note that consumed members have not to be calculated up-front. */ boolean isActuallyInherited(TMember m) { if (hasOwned()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, GETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(OWNED, FIELD) || hasOwnedOrNotAbstractMember(OWNED, SETTER) || hasOwnedOrNotAbstractMember(OWNED, METHOD)) { return false; } } else { return false; } } if (m.isField() || !m.isAbstract()) { return true; } if (hasImplemented()) { if (m.getMemberType() == GETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, GETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else if (m.getMemberType() == SETTER) { if (hasOwnedOrNotAbstractMember(IMPLEMENTED, FIELD) || hasOwnedOrNotAbstractMember(IMPLEMENTED, SETTER) || hasOwnedOrNotAbstractMember(IMPLEMENTED, METHOD)) { return false; } } else { return false; } } return true; } /** * Adds a member from the given source. */ public void add(int source, TMember member) { if (source == IMPLEMENTED && member.isStatic() && member.getContainingType() instanceof TInterface) { // no inheritance of static methods in interfaces // -> ignore this member in the matrix but keep it in helper field 'nonImplemented' to allow client code to // retrieve these members for showing better error messages, etc. nonImplemented.add(member); return; } int row = member.getMemberType().getValue(); MemberList list = memberMatrix[source][row]; if (list == null) { list = new MemberList<>(); memberMatrix[source][row] = list; } list.add(member); } @Override public String toString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } TMember first = allMembers().next(); StringBuilder strb = new StringBuilder("MemberMatrix: "); if (first.isStatic()) { strb.append("static "); } strb.append(first.getName()); strb.append("\n"); final int tab = 15; StringBuilder row = new StringBuilder(); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(COLS[source]); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append(row); for (MemberType type : MemberType.values()) { row.setLength(0); row.append(type.getName()).append(": "); tab(row, 10); for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { row.append(members(source, type).stream().map(m -> m.getContainingType().getName()) .collect(Collectors.joining(","))); if (source < 2) { tab(row, 10 + (1 + source) * tab); } } strb.append("\n").append(row); } strb.append("\n"); if (!consumed.isEmpty()) { strb.append("consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType() + " " + m.getContainingType().getName() + "." + m.getName() : "null") .collect(Collectors.joining(","))); } return strb.toString(); } private void tab(StringBuilder strb, int offset) { UtilN4.fill(strb, offset); strb.append('|'); } /** * Returns a one-line description, only for debugging purposes */ String toShortString() { if (!allMembers().hasNext()) { return "MemberMatrix not initialized yet."; } StringBuilder strb = new StringBuilder("["); for (MemberType type : MemberType.values()) { for (int source = 0; source < SOURCE_COUNT_WITHOUT_CONSUMED; source++) { strb.append(members(source, type).stream() .map(m -> m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName()) .collect(Collectors.joining(","))); } } if (!consumed.isEmpty()) { strb.append(", consumed: "); strb.append( consumed.stream() .map(m -> m != null ? m.getMemberType().getName().charAt(0) + " " + m.getContainingType().getName() : "null") .collect(Collectors.joining(","))); } strb.append("]"); return strb.toString(); } /** * Returns a possible override candidate, even a "wrong" candidate (e.g., a field for a method). Returns null if no * such candidate has been found. If possible, a non-private candidate is searched. */ public TMember possibleOverrideCandidateOrError(TMember member) { TMember result = null; for (TMember m : Iterables.concat(implemented(), inherited())) { if (!TypeUtils.isAccessorPair(member, m)) { if (m.getMemberAccessModifier() == MemberAccessModifier.PRIVATE) { result = m; } else { return m; } } } return result; } } |
blob | long method | t | t | f | long method | blob | 0 | 11345 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src/org/eclipse/n4js/validation/validators/utils/MemberMatrix.java/#L59-L597 | 1 | 1574 | 11345 | critical |
| 5400 | found (provided Javadoc comments without adding unecessary white space bloat). NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 15175 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 5400 | 15175 | minor | ||
| 2082 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AppService implements ApplicationService { private static final Logger logger = LoggerFactory.getLogger(ApplicationService.class); /** * Create an register an application service using the default alias {@link ApplicationService#ALIAS}. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @return Application service instance. */ public static ApplicationService createAndRegister(TopologyProvider provider, DirectSubmitter submitter) { AppService service = new AppService(provider, submitter, ALIAS); submitter.getServices().addService(ApplicationService.class, service); return service; } private final Map> applications = Collections.synchronizedMap(new HashMap<>()); private final TopologyProvider provider; private final DirectSubmitter submitter; /** * Create an {@code ApplicationService} instance. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @param alias Alias used to register the control MBean. */ public AppService(TopologyProvider provider, DirectSubmitter submitter, String alias) { this.provider = provider; this.submitter = submitter; ControlService cs = submitter.getServices().getService(ControlService.class); if (cs != null) cs.registerControl(ApplicationServiceMXBean.TYPE, ALIAS+System.currentTimeMillis(), alias, ApplicationServiceMXBean.class, new AppServiceControl(this)); } @Override public void registerTopology(String applicationName, BiConsumer builder) { if (applicationName == null || applicationName.isEmpty()) { throw new IllegalArgumentException(); } logger.trace("Register application name: {}", applicationName); applications.put(applicationName, builder); } /** * Create a new class loader for the jar and register any * topology application that is registered as a service provider. */ @Override public void registerJar(String jarURL, String jsonConfig) throws Exception { logger.trace("Register jar: {}", jarURL); // If it's a http URL download it otherwise use directly. URL url = new URL(jarURL); String protocol = url.getProtocol(); if ("http".equals(protocol) || "https".equals(protocol)) { url = downloadJar(url); } URLClassLoader loader = new URLClassLoader(new URL[] {url}); for (TopologyBuilder topoBuilder : ServiceLoader.load(TopologyBuilder.class, loader)) { registerTopology(topoBuilder.getName(), topoBuilder.getBuilder()); } } /** * Download an HTTP URL to a local file. * @param url URL to download from. * @return URL of the local file. */ private URL downloadJar(URL url) throws Exception { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Error response code for URL: {} : response code={}", url.toExternalForm(), responseCode); throw new IOException(); } String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); if (disposition != null) { // extracts file name from header field int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name from URL path String path = url.getPath(); if (!path.isEmpty()) { int lastSlash = path.lastIndexOf("/"); if (lastSlash == -1) fileName = path; else fileName = path.substring(lastSlash+1); } } // TODO - allow persistence across reboots // For now just store in a temp directory Path dir = Files.createTempDirectory("edgentjars"); File file; if (fileName.isEmpty()) file = File.createTempFile("edgent", "jar", dir.toFile()); else file = new File(dir.toFile(), fileName); InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); logger.trace("Register jar downloaded as: {}", file); return file.toURI().toURL(); } @Override public Set getApplicationNames() { synchronized (applications) { return new HashSet<>(applications.keySet()); } } BiConsumer getBuilder(String applicationName) { return applications.get(applicationName); } TopologyProvider getProvider() { return provider; } DirectSubmitter getSubmitter() { return submitter; } } |
blob | f | f | f | blob | 0 | 13073 | https://github.com/apache/incubator-edgent/blob/2e44089358175964650fed5e2bf4ad071b05b7d6/runtime/appservice/src/main/java/org/apache/edgent/runtime/appservice/AppService.java/#L62-L217 | 1 | 2082 | 13073 | minor | ||
| 2093 | YES I found bad smells. The bad smells are: 1. Feature envy: The class "DdbStreamComponent" contains accessors and setters that manipulate the fields of the "configuration" object instead of the class directly. This indicates a potential design flaw where the class "DdbStreamComponent" has a stronger dependency on the "configuration" object than on its own fields. 2. Long method: The "createEndpoint" method is quite long and contains multiple if statements, making it difficult to read, understand, and maintain. 3. Shotgun surgery: Changes to the "createEndpoint" method would likely require changes to be made in multiple places throughout the class, as it contains code that directly affects the behavior and properties of the "configuration" object. 4. Inconsistent naming conventions: The class "DdbStreamComponent" uses camelCase naming convention for its fields, while the "createEndpoint" method uses snake_case for its parameters. 5. Code repetition: The "createEndpoint" method contains code that sets the "tableName" property twice, first before the "if" statement and then inside the "if" statement. This code could be refactored to eliminate the repetition. 6. Inappropriate comments: The comment for the "setRegion" method does not provide any useful information, as it just repeats the name and description of the method. 7. Poor encapsulation: The class "DdbStreamComponent" directly exposes the "configuration" object to other classes, allowing them to manipulate its fields and potentially causing unexpected behavior. It would be better to encapsulate the "configuration" object and only provide access to it through getters and setters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component("aws-ddbstream") public class DdbStreamComponent extends DefaultComponent { @Metadata private String accessKey; @Metadata private String secretKey; @Metadata private String region; @Metadata(label = "advanced") private DdbStreamConfiguration configuration; public DdbStreamComponent() { this(null); } public DdbStreamComponent(CamelContext context) { super(context); this.configuration = new DdbStreamConfiguration(); registerExtension(new DdbStreamComponentVerifierExtension()); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { DdbStreamConfiguration configuration = this.configuration.copy(); configuration.setTableName(remaining); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Table name must be specified."); } configuration.setTableName(remaining); if (ObjectHelper.isEmpty(configuration.getAccessKey())) { setAccessKey(accessKey); } if (ObjectHelper.isEmpty(configuration.getSecretKey())) { setSecretKey(secretKey); } if (ObjectHelper.isEmpty(configuration.getRegion())) { setRegion(region); } if (configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("amazonDDBStreamsClient or accessKey and secretKey must be specified"); } DdbStreamEndpoint endpoint = new DdbStreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); return endpoint; } public DdbStreamConfiguration getConfiguration() { return configuration; } /** * The AWS DDB stream default configuration */ public void setConfiguration(DdbStreamConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return configuration.getAccessKey(); } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { configuration.setAccessKey(accessKey); } public String getSecretKey() { return configuration.getSecretKey(); } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { configuration.setSecretKey(secretKey); } public String getRegion() { return configuration.getRegion(); } /** * Amazon AWS Region */ public void setRegion(String region) { configuration.setRegion(region); } } |
blob | Feature envy: The class "DdbStreamComponent" contains accessors and setters that manipulate the fields of the "configuration" object instead of the class directly This indicates a potential design flaw where the class "DdbStreamComponent" has a stronger dependency on the "configuration" object than on its own fields2 Long method: The "createEndpoint" method is quite long and contains multiple if statements, making it difficult to read, understand, and maintain3 Shotgun surgery: Changes to the "createEndpoint" method would likely require changes to be made in multiple places throughout the class, as it contains code that directly affects the behavior and properties of the "configuration" object4 Inconsistent naming conventions: The class "DdbStreamComponent" uses camelCase naming convention for its fields, while the "createEndpoint" method uses snake_case for its parameters5 Code repetition: The "createEndpoint" method contains code that sets the "tableName" property twice, first before the "if" statement and then inside the "if" statement This code could be refactored to eliminate the repetition6 Inappropriate comments: The comment for the "setRegion" method does not provide any useful information, as it just repeats the name and description of the method7 Poor encapsulation: The class "DdbStreamComponent" directly exposes the "configuration" object to other classes, allowing them to manipulate its fields and potentially causing unexpected behavior It would be better to encapsulate the "configuration" object and only provide access to it through getters and setters | t | f | f | . Feature envy: The class "DdbStreamComponent" contains accessors and setters that manipulate the fields of the "configuration" object instead of the class directly. This indicates a potential design flaw where the class "DdbStreamComponent" has a stronger dependency on the "configuration" object than on its own fields.2. Long method: The "createEndpoint" method is quite long and contains multiple if statements, making it difficult to read, understand, and maintain.3. Shotgun surgery: Changes to the "createEndpoint" method would likely require changes to be made in multiple places throughout the class, as it contains code that directly affects the behavior and properties of the "configuration" object.4. Inconsistent naming conventions: The class "DdbStreamComponent" uses camelCase naming convention for its fields, while the "createEndpoint" method uses snake_case for its parameters.5. Code repetition: The "createEndpoint" method contains code that sets the "tableName" property twice, first before the "if" statement and then inside the "if" statement. This code could be refactored to eliminate the repetition.6. Inappropriate comments: The comment for the "setRegion" method does not provide any useful information, as it just repeats the name and description of the method.7. Poor encapsulation: The class "DdbStreamComponent" directly exposes the "configuration" object to other classes, allowing them to manipulate its fields and potentially causing unexpected behavior. It would be better to encapsulate the "configuration" object and only provide access to it through getters and setters. | blob | 0 | 13140 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamComponent.java/#L28-L122 | 2 | 2093 | 13140 | minor |
| 2291 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Long method2Feature envy | t | f | f | .Long method2.Feature envy | data class | 0 | 13942 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 2291 | 13942 | minor |
| 421 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 4241 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 2 | 421 | 4241 | major |
| 478 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
blob | data class | t | t | f | data class | blob | 0 | 4622 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 478 | 4622 | minor |
| 2587 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14990 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2587 | 14990 | minor |
| 4353 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11498 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 4353 | 11498 | minor |
| 1488 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11104 | https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 | 1 | 1488 | 11104 | major |
| 1937 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12472 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 1 | 1937 | 12472 | critical |
| 557 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
data class | long method | t | t | f | long method | data class | 0 | 5616 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 1 | 557 | 5616 | minor |
| 2475 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | Feature envy | t | f | f | . Feature envy | long method | 0 | 14585 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 2 | 2475 | 14585 | minor |
| 1839 | YES I found bad smells. The bad smells are: 1.Long method, 2.Feature envy, 3.Magic numbers, 4.Nested ternary operators, 5.Redundant conditional, 6.Shotgun surgery. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XmiWriterCasConsumer extends CasConsumer_ImplBase { /** * Name of configuration parameter that must be set to the path of a directory into which the * output files will be written. */ public static final String PARAM_OUTPUTDIR = "OutputDirectory"; private File mOutputDir; private int mDocNum; public void initialize() throws ResourceInitializationException { mDocNum = 0; mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * Processes the CAS which was populated by the TextAnalysisEngines. * In this case, the CAS is converted to XMI and written into the output file . * * @param aCAS * a CAS which has been populated by the TAEs * * @throws ResourceProcessException * if there is an error in processing the Resource * * @see org.apache.uima.collection.base_cpm.CasObjectProcessor#processCas(org.apache.uima.cas.CAS) */ public void processCas(CAS aCAS) throws ResourceProcessException { String modelFileName = null; JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // retrieve the filename of the input file from the CAS FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator(); File outFile = null; if (it.hasNext()) { SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next(); File inFile; try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += ".xmi"; outFile = new File(mOutputDir, outFileName); modelFileName = mOutputDir.getAbsolutePath() + "/" + inFile.getName() + ".ecore"; } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xmi"); } // serialize XCAS and write to output file try { writeXmi(jcas.getCas(), outFile, modelFileName); } catch (IOException e) { throw new ResourceProcessException(e); } catch (SAXException e) { throw new ResourceProcessException(e); } } /** * Serialize a CAS to a file in XMI format * * @param aCas * CAS to serialize * @param name * output file * @throws SAXException - * @throws Exception - * * @throws ResourceProcessException - */ private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException { FileOutputStream out = null; try { // write XMI out = new FileOutputStream(name); XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(out, false); ser.serialize(aCas, xmlSer.getContentHandler()); } finally { if (out != null) { out.close(); } } } } |
blob | Long method, 2Feature envy, 3Magic numbers, 4Nested ternary operators, 5Redundant conditional, 6Shotgun surgery | t | f | f | .Long method, 2.Feature envy, 3.Magic numbers, 4.Nested ternary operators, 5.Redundant conditional, 6.Shotgun surgery. | blob | 0 | 12146 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-examples/src/main/java/org/apache/uima/examples/xmi/XmiWriterCasConsumer.java/#L48-L148 | 2 | 1839 | 12146 | minor |
| 5732 | YES I found bad smells the bad smells are: 1. Data Class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Data Class | t | f | f | . Data Class | long method | 0 | 13493 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5732 | 13493 | critical |
| 2108 | { "message": "YES I found bad smells", "the bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13178 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 2108 | 13178 | minor |
| 4768 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12832 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 1 | 4768 | 12832 | minor |
| 5278 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Message is both Serializable and has additional methods that write/read from ByteBuffer. This is a violation of the Single Responsibility Principle. 4. Mix of field-based and property-based access. 5. Mix of private and public fields without clear distinction. 6. Use of hardcoded values instead of constants. 7. Unnecessary comments and empty methods that serve no purpose. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | Long method2 Feature envy3 Message is both Serializable and has additional methods that write/read from ByteBuffer This is a violation of the Single Responsibility Principle4 Mix of field-based and property-based access5 Mix of private and public fields without clear distinction6 Use of hardcoded values instead of constants7 Unnecessary comments and empty methods that serve no purpose | t | f | f | . Long method2. Feature envy3. Message is both Serializable and has additional methods that write/read from ByteBuffer. This is a violation of the Single Responsibility Principle.4. Mix of field-based and property-based access.5. Mix of private and public fields without clear distinction.6. Use of hardcoded values instead of constants.7. Unnecessary comments and empty methods that serve no purpose. | data class | 0 | 14761 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 5278 | 14761 | minor |
| 779 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7453 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 2 | 779 | 7453 | minor |
| 2618 | { "output": "YES I found bad smells, the bad smells are: Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
blob | data class | t | t | f | data class | blob | 0 | 15050 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 2618 | 15050 | minor |
| 684 | This code does not have bad smells. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class createJob_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createJob_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createJob_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | f | f | f | blob | 0 | 6614 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/AuroraSchedulerManager.java/#L2760-L2805 | 2 | 684 | 6614 | minor | ||
| 1264 | Yes I found bad smells the bad smells are: 1.Feature envy: The OpStats class uses many methods and fields from the LogEntry class, indicating that it should possibly be refactored into the same class. 2.Magic numbers: The values for the 'readTimeout', 'writeTimeout', 'position', 'entriesSkipped' variables are hard-coded instead of using constants, making it harder to maintain and understand. 3.Long method: The mutate() method is more than 25 lines long, indicating that it may be too complicated and should possibly be split into smaller methods. 4.Lazy class: The LogStream class has a lot of methods and fields that are not used, making it potentially unnecessary and indicating that it may need to be split or refactored. 5.Message comments: The comment "// N.B. HACK! ..." indicates a temporary workaround instead of a proper solution. 6.Long parameter list: The constructor for the LogStream class has several long parameters, which could be simplified using a builder pattern or dependency injection. 7.Magic strings: The OpStats constructor and other methods use non-descriptive string literals instead of constants, making it harder to understand and maintain. 8.Inappropriate intimacy: The LogEntry class has tight coupling with the LogStream class, making it hard to maintain and modify. 9.Inappropriate duplication: The code for handling TimeoutException and Log.WriterFailedException in mutate() and disableLog() methods is duplicated, indicating that it could possibly be refactored into a single method. 10.Inconsistent naming: The OpStats class has inconsistent naming for its fields and methods, making it harder to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
blob | Feature envy: The OpStats class uses many methods and fields from the LogEntry class, indicating that it should possibly be refactored into the same class2Magic numbers: The values for the 'readTimeout', 'writeTimeout', 'position', 'entriesSkipped' variables are hard-coded instead of using constants, making it harder to maintain and understand3Long method: The mutate() method is more than 25 lines long, indicating that it may be too complicated and should possibly be split into smaller methods4Lazy class: The LogStream class has a lot of methods and fields that are not used, making it potentially unnecessary and indicating that it may need to be split or refactored5Message comments: The comment "// NB HACK! " indicates a temporary workaround instead of a proper solution6Long parameter list: The constructor for the LogStream class has several long parameters, which could be simplified using a builder pattern or dependency injection7Magic strings: The OpStats constructor and other methods use non-descriptive string literals instead of constants, making it harder to understand and maintain8Inappropriate intimacy: The LogEntry class has tight coupling with the LogStream class, making it hard to maintain and modify9Inappropriate duplication: The code for handling TimeoutException and LogWriterFailedException in mutate() and disableLog() methods is duplicated, indicating that it could possibly be refactored into a single method | t | f | f | .Feature envy: The OpStats class uses many methods and fields from the LogEntry class, indicating that it should possibly be refactored into the same class.2.Magic numbers: The values for the 'readTimeout', 'writeTimeout', 'position', 'entriesSkipped' variables are hard-coded instead of using constants, making it harder to maintain and understand.3.Long method: The mutate() method is more than 25 lines long, indicating that it may be too complicated and should possibly be split into smaller methods.4.Lazy class: The LogStream class has a lot of methods and fields that are not used, making it potentially unnecessary and indicating that it may need to be split or refactored.5.Message comments: The comment "// N.B. HACK! ..." indicates a temporary workaround instead of a proper solution.6.Long parameter list: The constructor for the LogStream class has several long parameters, which could be simplified using a builder pattern or dependency injection.7.Magic strings: The OpStats constructor and other methods use non-descriptive string literals instead of constants, making it harder to understand and maintain.8.Inappropriate intimacy: The LogEntry class has tight coupling with the LogStream class, making it hard to maintain and modify.9.Inappropriate duplication: The code for handling TimeoutException and Log.WriterFailedException in mutate() and disableLog() methods is duplicated, indicating that it could possibly be refactored into a single method. | blob | 0 | 10540 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 2 | 1264 | 10540 | minor |
| 1438 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10968 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 1438 | 10968 | minor |
| 615 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
blob | data class | t | t | f | data class | blob | 0 | 6174 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 615 | 6174 | minor |
| 128 | {"response": "YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupByMergingQueryRunnerV2 implements QueryRunner { private static final Logger log = new Logger(GroupByMergingQueryRunnerV2.class); private static final String CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION = "mergeRunnersUsingChainedExecution"; private final GroupByQueryConfig config; private final Iterable> queryables; private final ListeningExecutorService exec; private final QueryWatcher queryWatcher; private final int concurrencyHint; private final BlockingPool mergeBufferPool; private final ObjectMapper spillMapper; private final String processingTmpDir; private final int mergeBufferSize; public GroupByMergingQueryRunnerV2( GroupByQueryConfig config, ExecutorService exec, QueryWatcher queryWatcher, Iterable> queryables, int concurrencyHint, BlockingPool mergeBufferPool, int mergeBufferSize, ObjectMapper spillMapper, String processingTmpDir ) { this.config = config; this.exec = MoreExecutors.listeningDecorator(exec); this.queryWatcher = queryWatcher; this.queryables = Iterables.unmodifiableIterable(Iterables.filter(queryables, Predicates.notNull())); this.concurrencyHint = concurrencyHint; this.mergeBufferPool = mergeBufferPool; this.spillMapper = spillMapper; this.processingTmpDir = processingTmpDir; this.mergeBufferSize = mergeBufferSize; } @Override public Sequence run(final QueryPlus queryPlus, final Map responseContext) { final GroupByQuery query = (GroupByQuery) queryPlus.getQuery(); final GroupByQueryConfig querySpecificConfig = config.withOverrides(query); // CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION is here because realtime servers use nested mergeRunners calls // (one for the entire query and one for each sink). We only want the outer call to actually do merging with a // merge buffer, otherwise the query will allocate too many merge buffers. This is potentially sub-optimal as it // will involve materializing the results for each sink before starting to feed them into the outer merge buffer. // I'm not sure of a better way to do this without tweaking how realtime servers do queries. final boolean forceChainedExecution = query.getContextBoolean( CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, false ); final QueryPlus queryPlusForRunners = queryPlus .withQuery( query.withOverriddenContext(ImmutableMap.of(CTX_KEY_MERGE_RUNNERS_USING_CHAINED_EXECUTION, true)) ) .withoutThreadUnsafeState(); if (QueryContexts.isBySegment(query) || forceChainedExecution) { ChainedExecutionQueryRunner runner = new ChainedExecutionQueryRunner<>(exec, queryWatcher, queryables); return runner.run(queryPlusForRunners, responseContext); } final boolean isSingleThreaded = querySpecificConfig.isSingleThreaded(); final AggregatorFactory[] combiningAggregatorFactories = new AggregatorFactory[query.getAggregatorSpecs().size()]; for (int i = 0; i < query.getAggregatorSpecs().size(); i++) { combiningAggregatorFactories[i] = query.getAggregatorSpecs().get(i).getCombiningFactory(); } final File temporaryStorageDirectory = new File( processingTmpDir, StringUtils.format("druid-groupBy-%s_%s", UUID.randomUUID(), query.getId()) ); final int priority = QueryContexts.getPriority(query); // Figure out timeoutAt time now, so we can apply the timeout to both the mergeBufferPool.take and the actual // query processing together. final long queryTimeout = QueryContexts.getTimeout(query); final boolean hasTimeout = QueryContexts.hasTimeout(query); final long timeoutAt = System.currentTimeMillis() + queryTimeout; return new BaseSequence<>( new BaseSequence.IteratorMaker>() { @Override public CloseableGrouperIterator make() { final List resources = new ArrayList<>(); try { final LimitedTemporaryStorage temporaryStorage = new LimitedTemporaryStorage( temporaryStorageDirectory, querySpecificConfig.getMaxOnDiskStorage() ); final ReferenceCountingResourceHolder temporaryStorageHolder = ReferenceCountingResourceHolder.fromCloseable(temporaryStorage); resources.add(temporaryStorageHolder); // If parallelCombine is enabled, we need two merge buffers for parallel aggregating and parallel combining final int numMergeBuffers = querySpecificConfig.getNumParallelCombineThreads() > 1 ? 2 : 1; final List> mergeBufferHolders = getMergeBuffersHolder( numMergeBuffers, hasTimeout, timeoutAt ); resources.addAll(mergeBufferHolders); final ReferenceCountingResourceHolder mergeBufferHolder = mergeBufferHolders.get(0); final ReferenceCountingResourceHolder combineBufferHolder = numMergeBuffers == 2 ? mergeBufferHolders.get(1) : null; Pair, Accumulator> pair = RowBasedGrouperHelper.createGrouperAccumulatorPair( query, false, null, config, Suppliers.ofInstance(mergeBufferHolder.get()), combineBufferHolder, concurrencyHint, temporaryStorage, spillMapper, combiningAggregatorFactories, exec, priority, hasTimeout, timeoutAt, mergeBufferSize ); final Grouper grouper = pair.lhs; final Accumulator accumulator = pair.rhs; grouper.init(); final ReferenceCountingResourceHolder> grouperHolder = ReferenceCountingResourceHolder.fromCloseable(grouper); resources.add(grouperHolder); ListenableFuture> futures = Futures.allAsList( Lists.newArrayList( Iterables.transform( queryables, new Function, ListenableFuture>() { @Override public ListenableFuture apply(final QueryRunner input) { if (input == null) { throw new ISE( "Null queryRunner! Looks to be some segment unmapping action happening" ); } ListenableFuture future = exec.submit( new AbstractPrioritizedCallable(priority) { @Override public AggregateResult call() { try ( // These variables are used to close releasers automatically. @SuppressWarnings("unused") Releaser bufferReleaser = mergeBufferHolder.increment(); @SuppressWarnings("unused") Releaser grouperReleaser = grouperHolder.increment() ) { final AggregateResult retVal = input.run(queryPlusForRunners, responseContext) .accumulate( AggregateResult.ok(), accumulator ); // Return true if OK, false if resources were exhausted. return retVal; } catch (QueryInterruptedException e) { throw e; } catch (Exception e) { log.error(e, "Exception with one of the sequences!"); throw new RuntimeException(e); } } } ); if (isSingleThreaded) { waitForFutureCompletion( query, Futures.allAsList(ImmutableList.of(future)), hasTimeout, timeoutAt - System.currentTimeMillis() ); } return future; } } ) ) ); if (!isSingleThreaded) { waitForFutureCompletion(query, futures, hasTimeout, timeoutAt - System.currentTimeMillis()); } return RowBasedGrouperHelper.makeGrouperIterator( grouper, query, new Closeable() { @Override public void close() { for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } } } ); } catch (Throwable e) { // Exception caught while setting up the iterator; release resources. for (Closeable closeable : Lists.reverse(resources)) { CloseQuietly.close(closeable); } throw e; } } @Override public void cleanup(CloseableGrouperIterator iterFromMake) { iterFromMake.close(); } } ); } private List> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List> mergeBufferHolder; // This will potentially block if there are no merge buffers left in the pool. if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } } private void waitForFutureCompletion( GroupByQuery query, ListenableFuture> future, boolean hasTimeout, long timeout ) { try { if (queryWatcher != null) { queryWatcher.registerQuery(query, future); } if (hasTimeout && timeout <= 0) { throw new TimeoutException(); } final List results = hasTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get(); for (AggregateResult result : results) { if (!result.isOk()) { future.cancel(true); throw new ResourceLimitExceededException(result.getReason()); } } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (CancellationException e) { throw new QueryInterruptedException(e); } catch (TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1606 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/GroupByMergingQueryRunnerV2.java/#L72-L392 | 2 | 128 | 1606 | critical |
| 3368 | . NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 6394 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 3368 | 6394 | major | ||
| 1377 | { "error": "The provided Java code is too lengthy for me to analyze. Please provide a shorter code snippet for analysis." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Not specified | f | f | f | false | 0 | 10811 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1377 | 10811 | minor | |
| 2539 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14771 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 2539 | 14771 | major |
| 820 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LibraryBreadcrumbNodeProvider extends DesignerBreadcrumbNodeProvider { public boolean validate( Object element ) { if ( getEditPart( element ) == null // || getEditPart( element ) instanceof EmptyEditPart ) return false; return true; } public EditPart getEditPart( Object element ) { // EditPart editPart = super.getEditPart( element ); // if ( editPart == null || editPart instanceof EmptyEditPart ) // return null; return super.getEditPart( element ); } @Override public Object[] getChildren( Object element ) { if ( getRealModel( element ) instanceof LibraryHandle ) { return ( (LibraryHandle) getRealModel( element ) ).getComponents( ) .getContents( ) .toArray( ); } List children = new ArrayList( ); children.addAll( Arrays.asList( super.getChildren( element ) ) ); for ( int i = 0; i < children.size( ); i++ ) { if ( children.get( i ) instanceof EmptyEditPart ) { children.remove( i ); i--; } } return children.toArray( ); } @Override public String getText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeDisplayName( object ); } } return super.getText( element ); } @Override public Image getImage( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return null; return provider.getNodeIcon( object ); } } return super.getImage( element ); } @Override public String getTooltipText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeTooltip( object ); } } return super.getTooltipText( element ); } } |
blob | data class | t | t | f | data class | blob | 0 | 7679 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.lib/src/org/eclipse/birt/report/designer/internal/lib/providers/LibraryBreadcrumbNodeProvider.java/#L31-L127 | 1 | 820 | 7679 | major |
| 460 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 4462 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 2 | 460 | 4462 | minor |
| 895 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UpdateErrors implements Message { /** */ private static final long serialVersionUID = 0L; /** Failed keys. */ @GridToStringInclude @GridDirectCollection(KeyCacheObject.class) private List failedKeys; /** Update error. */ @GridDirectTransient @GridToStringInclude private IgniteCheckedException err; /** Serialized update error. */ private byte[] errBytes; /** * */ public UpdateErrors() { // No-op. } /** * @param err Error. */ public UpdateErrors(IgniteCheckedException err) { assert err != null; this.err = err; } /** * @param err Error. */ public void onError(IgniteCheckedException err){ this.err = err; } /** * @return Error. */ public IgniteCheckedException error() { return err; } /** * @return Failed keys. */ public Collection failedKeys() { return failedKeys; } /** * Adds key to collection of failed keys. * * @param key Key to add. * @param e Error cause. */ void addFailedKey(KeyCacheObject key, Throwable e) { if (failedKeys == null) failedKeys = new ArrayList<>(); failedKeys.add(key); if (err == null) err = new IgniteCheckedException("Failed to update keys."); err.addSuppressed(e); } /** * @param keys Keys. * @param e Error. */ void addFailedKeys(Collection keys, Throwable e) { if (failedKeys == null) failedKeys = new ArrayList<>(keys.size()); failedKeys.addAll(keys); if (err == null) err = new IgniteCheckedException("Failed to update keys on primary node."); err.addSuppressed(e); } /** {@inheritDoc} */ void prepareMarshal(GridCacheMessage msg, GridCacheContext cctx) throws IgniteCheckedException { msg.prepareMarshalCacheObjects(failedKeys, cctx); if (errBytes == null) errBytes = U.marshal(cctx.marshaller(), err); } /** {@inheritDoc} */ void finishUnmarshal(GridCacheMessage msg, GridCacheContext cctx, ClassLoader ldr) throws IgniteCheckedException { msg.finishUnmarshalCacheObjects(failedKeys, cctx, ldr); if (errBytes != null && err == null) err = U.unmarshal(cctx.marshaller(), errBytes, U.resolveClassLoader(ldr, cctx.gridConfig())); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeByteArray("errBytes", errBytes)) return false; writer.incrementState(); case 1: if (!writer.writeCollection("failedKeys", failedKeys, MessageCollectionItemType.MSG)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: errBytes = reader.readByteArray("errBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: failedKeys = reader.readCollection("failedKeys", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(UpdateErrors.class); } /** {@inheritDoc} */ @Override public short directType() { return -49; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 2; } /** {@inheritDoc} */ @Override public void onAckReceived() { // No-op. } /** {@inheritDoc} */ @Override public String toString() { return S.toString(UpdateErrors.class, this); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8111 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/UpdateErrors.java/#L41-L222 | 2 | 895 | 8111 | minor |
| 282 | { "message": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } } |
blob | Long Method, 2 Data Class" } | t | f | f | . Long Method, 2. Data Class" } | blob | 0 | 3020 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 | 1 | 282 | 3020 | major |
| 1366 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | long method | t | t | f | long method | data class | 0 | 10787 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 1366 | 10787 | major |
| 1005 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9255 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1005 | 9255 | minor |
| 860 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConnectionLoadBalanceServer { private static final Logger logger = LoggerFactory.getLogger(ConnectionLoadBalanceServer.class); private final String hostname; private final int port; private final SSLContext sslContext; private final ExecutorService threadPool; private final LoadBalanceProtocol loadBalanceProtocol; private final int connectionTimeoutMillis; private final int numThreads; private final EventReporter eventReporter; private volatile Set communicationActions = Collections.emptySet(); private final BlockingQueue connectionQueue = new LinkedBlockingQueue<>(); private volatile AcceptConnection acceptConnection; private volatile ServerSocket serverSocket; private volatile boolean stopped = true; public ConnectionLoadBalanceServer(final String hostname, final int port, final SSLContext sslContext, final int numThreads, final LoadBalanceProtocol loadBalanceProtocol, final EventReporter eventReporter, final int connectionTimeoutMillis) { this.hostname = hostname; this.port = port; this.sslContext = sslContext; this.loadBalanceProtocol = loadBalanceProtocol; this.connectionTimeoutMillis = connectionTimeoutMillis; this.numThreads = numThreads; this.eventReporter = eventReporter; threadPool = new FlowEngine(numThreads, "Load Balance Server"); } public void start() throws IOException { if (!stopped) { return; } stopped = false; if (serverSocket != null) { return; } try { serverSocket = createServerSocket(); } catch (final Exception e) { throw new IOException("Could not begin listening for incoming connections in order to load balance data across the cluster. Please verify the values of the " + "'nifi.cluster.load.balance.port' and 'nifi.cluster.load.balance.host' properties as well as the 'nifi.security.*' properties", e); } final Set actions = new HashSet<>(numThreads); for (int i=0; i < numThreads; i++) { final CommunicateAction action = new CommunicateAction(loadBalanceProtocol); actions.add(action); threadPool.submit(action); } this.communicationActions = actions; acceptConnection = new AcceptConnection(serverSocket); final Thread receiveConnectionThread = new Thread(acceptConnection); receiveConnectionThread.setName("Receive Queue Load-Balancing Connections"); receiveConnectionThread.start(); } public int getPort() { return serverSocket.getLocalPort(); } public void stop() { stopped = false; threadPool.shutdown(); if (acceptConnection != null) { acceptConnection.stop(); } communicationActions.forEach(CommunicateAction::stop); Socket socket; while ((socket = connectionQueue.poll()) != null) { try { socket.close(); logger.info("{} Closed connection to {} on Server stop", this, socket.getRemoteSocketAddress()); } catch (final IOException ioe) { logger.warn("Failed to properly close socket to " + socket.getRemoteSocketAddress(), ioe); } } } private ServerSocket createServerSocket() throws IOException { final InetAddress inetAddress = hostname == null ? null : InetAddress.getByName(hostname); if (sslContext == null) { return new ServerSocket(port, 50, InetAddress.getByName(hostname)); } else { final ServerSocket serverSocket = sslContext.getServerSocketFactory().createServerSocket(port, 50, inetAddress); ((SSLServerSocket) serverSocket).setNeedClientAuth(true); return serverSocket; } } private class CommunicateAction implements Runnable { private final LoadBalanceProtocol loadBalanceProtocol; private volatile boolean stopped = false; public CommunicateAction(final LoadBalanceProtocol loadBalanceProtocol) { this.loadBalanceProtocol = loadBalanceProtocol; } public void stop() { this.stopped = true; } @Override public void run() { String peerDescription = ""; while (!stopped) { Socket socket = null; try { socket = connectionQueue.poll(1, TimeUnit.SECONDS); if (socket == null) { continue; } peerDescription = socket.getRemoteSocketAddress().toString(); if (socket.isClosed()) { logger.debug("Connection to Peer {} is closed. Will not attempt to communicate over this Socket.", peerDescription); continue; } logger.debug("Receiving FlowFiles from Peer {}", peerDescription); loadBalanceProtocol.receiveFlowFiles(socket); if (socket.isConnected()) { logger.debug("Finished receiving FlowFiles from Peer {}. Will recycle connection.", peerDescription); connectionQueue.offer(socket); } else { logger.debug("Finished receiving FlowFiles from Peer {}. Socket is no longer connected so will not recycle connection.", peerDescription); } } catch (final Exception e) { if (socket != null) { try { socket.close(); } catch (final IOException ioe) { e.addSuppressed(ioe); } } logger.error("Failed to communicate with Peer {}", peerDescription, e); eventReporter.reportEvent(Severity.ERROR, "Load Balanced Connection", "Failed to receive FlowFiles for Load Balancing due to " + e); } } logger.info("Connection Load Balance Server shutdown. Will no longer handle incoming requests."); } } private class AcceptConnection implements Runnable { private final ServerSocket serverSocket; private volatile boolean stopped = false; public AcceptConnection(final ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void stop() { stopped = true; } @Override public void run() { try { serverSocket.setSoTimeout(1000); } catch (final Exception e) { logger.error("Failed to set soTimeout on Server Socket for Load Balancing data across cluster", e); } while (!stopped) { try { final Socket socket; try { socket = serverSocket.accept(); } catch (final SocketTimeoutException ste) { continue; } socket.setSoTimeout(connectionTimeoutMillis); connectionQueue.offer(socket); } catch (final Exception e) { logger.error("{} Failed to accept connection from other node in cluster", ConnectionLoadBalanceServer.this, e); } } try { serverSocket.close(); } catch (final Exception e) { logger.warn("Failed to properly shutdown Server Socket for Load Balancing", e); } } } @Override public String toString() { return "ConnectionLoadBalanceServer[hostname=" + hostname + ", port=" + port + ", secure=" + (sslContext != null) + "]"; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 7901 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/clustered/server/ConnectionLoadBalanceServer.java/#L42-L251 | 1 | 860 | 7901 | major |
| 1506 | YES, I found bad smellsthe bad smells are: 1. Getter and setter methods for all variables. 2. Class name is not descriptive. 3. Code is not following SOLID principles. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Getter and setter methods for all variables2 Class name is not descriptive3 Code is not following SOLID principles | t | f | f | . Getter and setter methods for all variables.2. Class name is not descriptive.3. Code is not following SOLID principles. | data class | 0 | 11150 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1506 | 11150 | critical |
| 1034 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 9396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 1034 | 9396 | minor | ||
| 672 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ContextMenuProvider extends MenuManager implements IMenuListener { private EditPartViewer viewer; /** * Constructs a context menu for the specified EditPartViewer. * * @param viewer * the editpart viewer */ public ContextMenuProvider(EditPartViewer viewer) { setViewer(viewer); addMenuListener(this); setRemoveAllWhenShown(true); } /** * Called when the menu is about to show. Subclasses must implement this * method to populate the menu each time it is shown. * * @param menu * this parameter is actually this object */ public abstract void buildContextMenu(IMenuManager menu); /** * Returns the EditPartViewer * * @return the viewer */ protected EditPartViewer getViewer() { return viewer; } /** * @see IMenuListener#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { buildContextMenu(menu); } /** * Sets the editpart viewer. Called during construction. * * @param viewer * the viewer */ protected void setViewer(EditPartViewer viewer) { this.viewer = viewer; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6563 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.gef/src/org/eclipse/gef/ContextMenuProvider.java/#L24-L76 | 2 | 672 | 6563 | minor |
| 2650 | { "output": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | blob | t | t | f | blob | long method | 0 | 15167 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 2650 | 15167 | minor |
| 2344 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14186 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 2344 | 14186 | major |
| 237 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractBraveClientProvider extends AbstractTracingProvider { protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBraveClientProvider.class); protected static final String TRACE_SPAN = "org.apache.cxf.tracing.client.brave.span"; private final HttpTracing brave; public AbstractBraveClientProvider(final HttpTracing brave) { this.brave = brave; } protected TraceScopeHolder startTraceSpan(final Map> requestHeaders, URI uri, String method) { final Request request = HttpAdapterFactory.request(requestHeaders, uri, method); final HttpClientAdapter adapter = HttpClientAdapterFactory.create(request); final HttpClientHandler handler = HttpClientHandler.create(brave, adapter); final Span span = handler.handleSend( brave .tracing() .propagation() .injector(inject(requestHeaders)), request); // In case of asynchronous client invocation, the span should be detached as JAX-RS // client request / response filters are going to be executed in different threads. SpanInScope scope = null; if (!isAsyncInvocation() && span != null) { scope = brave.tracing().tracer().withSpanInScope(span); } return new TraceScopeHolder(new TraceScope(span, scope), scope == null /* detached */); } private Setter inject(final Map> requestHeaders) { return (carrier, key, value) -> { if (!requestHeaders.containsKey(key)) { requestHeaders.put(key, Collections.singletonList(value)); } }; } private boolean isAsyncInvocation() { return !PhaseInterceptorChain.getCurrentMessage().getExchange().isSynchronous(); } protected void stopTraceSpan(final TraceScopeHolder holder, final int responseStatus) { if (holder == null) { return; } final TraceScope scope = holder.getScope(); if (scope != null) { try { // If the client invocation was asynchronous , the trace span has been created // in another thread and should be re-attached to the current one. if (holder.isDetached()) { brave.tracing().tracer().joinSpan(scope.getSpan().context()); } final Response response = HttpAdapterFactory.response(responseStatus); final HttpClientAdapter adapter = HttpClientAdapterFactory.create(response); final HttpClientHandler handler = HttpClientHandler.create(brave, adapter); handler.handleReceive(response, null, scope.getSpan()); } finally { scope.close(); } } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 2571 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/integration/tracing/tracing-brave/src/main/java/org/apache/cxf/tracing/brave/AbstractBraveClientProvider.java/#L41-L111 | 1 | 237 | 2571 | minor |
| 245 | { "message": "YES I found bad smells", "bad smells are": [ "1. Data Class", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
blob | 1. data class, 2. long method | t | t | f | 1. data class, 2. long method | blob | 0 | 2653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 1 | 245 | 2653 | minor |
| 2388 | {"message": "YES I found bad smells. The bad smells are: Blob, Data Class, Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
feature envy | blob, data class, long method | t | t | f | blob, data class, long method | feature envy | 0 | 14352 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2388 | 14352 | minor |
| 171 | {"message": "YES I found bad smells", "bad smells are:": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2036 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 171 | 2036 | minor |
| 2352 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14223 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2352 | 14223 | minor | ||
| 1741 | YES I found bad smells the bad smells are: 1. Duplication 2. Long method 3. Feature envy 4. Inappropriate intimacy 5. Lazy class 6. Data class 7. Switch statement 8. Primitive obsession 9. Magic number 10. Long parameter list 11. Incomplete library class 12. Shotgun surgery (methods referencing multiple variables outside of their own class) 13. Dead code (unused methods) 14. Violation of the single responsibility principle (multiple methods handling different responsibilities) 15. Inconsistent naming and spacing conventions 16. Inefficient use of comments 17. Lack of exception handling 18. Inconsistent use of data types (mixing int and double without clear reason) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
blob | Duplication2 Long method3 Feature envy4 Inappropriate intimacy5 Lazy class6 Data class7 Switch statement8 Primitive obsession9 Magic number | t | f | f | . Duplication2. Long method3. Feature envy4. Inappropriate intimacy5. Lazy class6. Data class7. Switch statement8. Primitive obsession9. Magic number | blob | 0 | 11842 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 2 | 1741 | 11842 | major |
| 278 | of YES I Found bad smells: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | Long method2 Duplicate code | t | f | f | . Long method2. Duplicate code | blob | 0 | 2984 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 2 | 278 | 2984 | minor |
| 3904 | { "status": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | long method | t | t | f | long method | blob | 0 | 10221 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 1 | 3904 | 10221 | minor |
| 2508 | YES, I found bad smells the bad smells are: 1.Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long Method | t | f | f | .Long Method | data class | 0 | 14675 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 2 | 2508 | 14675 | minor |
| 1208 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10291 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 | 1 | 1208 | 10291 | major |
| 1001 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } } |
data class | Long method, 2 Feature envy,3 Duplicate code | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code. | data class | 0 | 9189 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 | 2 | 1001 | 9189 | major |
| 492 | YES, I found bad smells. The bad smells are: 1. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | Feature envy | t | f | f | . Feature envy. | data class | 0 | 4936 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 2 | 492 | 4936 | minor |
| 1592 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
long method | t | f | f | long method | 0 | 11396 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 1 | 1592 | 11396 | minor | ||
| 1869 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 12245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 2 | 1869 | 12245 | major |
| 1044 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9447 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1044 | 9447 | major |
| 1065 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | Long Method 2 Feature Envy | t | f | f | . Long Method 2. Feature Envy | data class | 0 | 9567 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 2 | 1065 | 9567 | minor |
| 3750 | YES I found bad smells The bad smells are: 1. Long method 2. Exception handling within the method instead of delegating it to another class or method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, PhoenixIndexFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } |
feature envy | Long method2 Exception handling within the method instead of delegating it to another class or method | t | f | f | . Long method2. Exception handling within the method instead of delegating it to another class or method. | feature envy | 0 | 9355 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/write/IndexWriter.java/#L87-L100 | 2 | 3750 | 9355 | major |
| 2121 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13213 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 1 | 2121 | 13213 | minor |
| 439 | YES I found bad smells The bad smells are: 1. Nested class 2. Long method 3. Long class 4. Feature envy 5. Incomplete error handling 6. Duplicate code 7. Magic numbers 8. Poor naming of variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Nested class 2 Long method 3 Long class 4 Feature envy 5 Incomplete error handling 6 Duplicate code 7 Magic numbers 8 Poor naming of variables and methods | t | f | f | . Nested class 2. Long method 3. Long class 4. Feature envy 5. Incomplete error handling 6. Duplicate code 7. Magic numbers 8. Poor naming of variables and methods | data class | 0 | 4294 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 2 | 439 | 4294 | major |
| 5757 | NO, I did not find any bad smell. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
feature envy | f | f | f | feature envy | 0 | 14502 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5757 | 14502 | minor | ||
| 2339 | {"result": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 14172 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 2 | 2339 | 14172 | minor |
| 1294 | { "message": "YES I found bad smells the bad smells are:", "bad smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 10624 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1294 | 10624 | minor |
| 297 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 3123 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 1 | 297 | 3123 | minor |
| 2248 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13661 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 2 | 2248 | 13661 | minor | ||
| 4282 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11274 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 1 | 4282 | 11274 | minor |
| 2544 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14788 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 | 1 | 2544 | 14788 | minor |
| 2000 | {"response": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetadataProvider { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MetadataProvider.class); private static final String IN_FUNCTION = "in"; private static final String LIKE_FUNCTION = "like"; private static final String AND_FUNCTION = "booleanand"; private static final String OR_FUNCTION = "booleanor"; /** * @return Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ public static Runnable catalogs(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { return new CatalogsProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the schema metadata for given {@link GetSchemasReq} and sends response at the end. */ public static Runnable schemas(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { return new SchemasProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the table metadata for given {@link GetTablesReq} and sends response at the end. */ public static Runnable tables(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { return new TablesProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the column metadata for given {@link GetColumnsReq} and sends response at the end. */ public static Runnable columns(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { return new ColumnsProvider(session, dContext, req, responseSender); } /** * Super class for all metadata provider runnable classes. */ private abstract static class MetadataRunnable implements Runnable { protected final UserSession session; private final ResponseSender responseSender; private final DrillbitContext dContext; private MetadataRunnable(final UserSession session, final DrillbitContext dContext, final ResponseSender responseSender) { this.session = Preconditions.checkNotNull(session); this.dContext = Preconditions.checkNotNull(dContext); this.responseSender = Preconditions.checkNotNull(responseSender); } @Override public void run() { try(SchemaTreeProvider schemaTreeProvider = new SchemaTreeProvider(dContext)) { responseSender.send(runInternal(session, schemaTreeProvider)); } catch (final Throwable error) { logger.error("Unhandled metadata provider error", error); } } /** * @return A {@link Response} message. Response must be returned in any case. */ protected abstract Response runInternal(UserSession session, SchemaTreeProvider schemaProvider); public DrillConfig getConfig() { return dContext.getConfig(); } } /** * Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ private static class CatalogsProvider extends MetadataRunnable { private static final Ordering CATALOGS_ORDERING = new Ordering() { @Override public int compare(CatalogMetadata left, CatalogMetadata right) { return Ordering.natural().compare(left.getCatalogName(), right.getCatalogName()); } }; private final GetCatalogsReq req; public CatalogsProvider(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetCatalogsResp.Builder respBuilder = GetCatalogsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(CATALOGS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Catalog c : records) { final CatalogMetadata.Builder catBuilder = CatalogMetadata.newBuilder(); catBuilder.setCatalogName(c.CATALOG_NAME); catBuilder.setDescription(c.CATALOG_DESCRIPTION); catBuilder.setConnect(c.CATALOG_CONNECT); metadata.add(catBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, CATALOGS_ORDERING); respBuilder.addAllCatalogs(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get catalogs", e)); } finally { return new Response(RpcType.CATALOGS, respBuilder.build()); } } } private static class SchemasProvider extends MetadataRunnable { private static final Ordering SCHEMAS_ORDERING = new Ordering() { @Override public int compare(SchemaMetadata left, SchemaMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .result(); }; }; private final GetSchemasReq req; private SchemasProvider(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetSchemasResp.Builder respBuilder = GetSchemasResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(SCHEMATA, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Schema s : records) { final SchemaMetadata.Builder schemaBuilder = SchemaMetadata.newBuilder(); schemaBuilder.setCatalogName(s.CATALOG_NAME); schemaBuilder.setSchemaName(s.SCHEMA_NAME); schemaBuilder.setOwner(s.SCHEMA_OWNER); schemaBuilder.setType(s.TYPE); schemaBuilder.setMutable(s.IS_MUTABLE); metadata.add(schemaBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, SCHEMAS_ORDERING); respBuilder.addAllSchemas(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get schemas", e)); } finally { return new Response(RpcType.SCHEMAS, respBuilder.build()); } } } private static class TablesProvider extends MetadataRunnable { private static final Ordering TABLES_ORDERING = new Ordering() { @Override public int compare(TableMetadata left, TableMetadata right) { return ComparisonChain.start() .compare(left.getType(), right.getType()) .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .result(); } }; private final GetTablesReq req; private TablesProvider(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, req.getTableTypeFilterCount() != 0 ? req.getTableTypeFilterList() : null, null); try { final PojoRecordReader records = getPojoRecordReader(TABLES, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Table t : records) { final TableMetadata.Builder tableBuilder = TableMetadata.newBuilder(); tableBuilder.setCatalogName(t.TABLE_CATALOG); tableBuilder.setSchemaName(t.TABLE_SCHEMA); tableBuilder.setTableName(t.TABLE_NAME); tableBuilder.setType(t.TABLE_TYPE); metadata.add(tableBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, TABLES_ORDERING); respBuilder.addAllTables(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get tables", e)); } finally { return new Response(RpcType.TABLES, respBuilder.build()); } } } private static class ColumnsProvider extends MetadataRunnable { private static final Ordering COLUMNS_ORDERING = new Ordering() { @Override public int compare(ColumnMetadata left, ColumnMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .compare(left.getOrdinalPosition(), right.getOrdinalPosition()) .result(); } }; private final GetColumnsReq req; private ColumnsProvider(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetColumnsResp.Builder respBuilder = GetColumnsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, null, req.hasColumnNameFilter() ? req.getColumnNameFilter() : null ); try { final PojoRecordReader records = getPojoRecordReader(COLUMNS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Column c : records) { final ColumnMetadata.Builder columnBuilder = ColumnMetadata.newBuilder(); columnBuilder.setCatalogName(c.TABLE_CATALOG); columnBuilder.setSchemaName(c.TABLE_SCHEMA); columnBuilder.setTableName(c.TABLE_NAME); columnBuilder.setColumnName(c.COLUMN_NAME); columnBuilder.setOrdinalPosition(c.ORDINAL_POSITION); if (c.COLUMN_DEFAULT != null) { columnBuilder.setDefaultValue(c.COLUMN_DEFAULT); } if ("YES".equalsIgnoreCase(c.IS_NULLABLE)) { columnBuilder.setIsNullable(true); } else { columnBuilder.setIsNullable(false); } columnBuilder.setDataType(c.DATA_TYPE); if (c.CHARACTER_MAXIMUM_LENGTH != null) { columnBuilder.setCharMaxLength(c.CHARACTER_MAXIMUM_LENGTH); } if (c.CHARACTER_OCTET_LENGTH != null) { columnBuilder.setCharOctetLength(c.CHARACTER_OCTET_LENGTH); } if (c.NUMERIC_SCALE != null) { columnBuilder.setNumericScale(c.NUMERIC_SCALE); } if (c.NUMERIC_PRECISION != null) { columnBuilder.setNumericPrecision(c.NUMERIC_PRECISION); } if (c.NUMERIC_PRECISION_RADIX != null) { columnBuilder.setNumericPrecisionRadix(c.NUMERIC_PRECISION_RADIX); } if (c.DATETIME_PRECISION != null) { columnBuilder.setDateTimePrecision(c.DATETIME_PRECISION); } if (c.INTERVAL_TYPE != null) { columnBuilder.setIntervalType(c.INTERVAL_TYPE); } if (c.INTERVAL_PRECISION != null) { columnBuilder.setIntervalPrecision(c.INTERVAL_PRECISION); } if (c.COLUMN_SIZE != null) { columnBuilder.setColumnSize(c.COLUMN_SIZE); } metadata.add(columnBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, COLUMNS_ORDERING); respBuilder.addAllColumns(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get columns", e)); } finally { return new Response(RpcType.COLUMNS, respBuilder.build()); } } } /** * Helper method to create a {@link InfoSchemaFilter} that combines the given filters with an AND. * * @param catalogNameFilter Optional filter on catalog name * @param schemaNameFilter Optional filter on schema name * @param tableNameFilter Optional filter on table name * @param tableTypeFilter Optional filter on table type * @param columnNameFilter Optional filter on column name * @return information schema filter */ private static InfoSchemaFilter createInfoSchemaFilter(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, List tableTypeFilter, LikeFilter columnNameFilter) { FunctionExprNode exprNode = createLikeFunctionExprNode(CATS_COL_CATALOG_NAME, catalogNameFilter); // schema names are case insensitive in Drill and stored in lower case // convert like filter condition elements to lower case if (schemaNameFilter != null) { LikeFilter.Builder builder = LikeFilter.newBuilder(); if (schemaNameFilter.hasPattern()) { builder.setPattern(schemaNameFilter.getPattern().toLowerCase()); } if (schemaNameFilter.hasEscape()) { builder.setEscape(schemaNameFilter.getEscape().toLowerCase()); } schemaNameFilter = builder.build(); } exprNode = combineFunctions(AND_FUNCTION, exprNode, combineFunctions(OR_FUNCTION, createLikeFunctionExprNode(SHRD_COL_TABLE_SCHEMA, schemaNameFilter), createLikeFunctionExprNode(SCHS_COL_SCHEMA_NAME, schemaNameFilter) ) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(SHRD_COL_TABLE_NAME, tableNameFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createInFunctionExprNode(TBLS_COL_TABLE_TYPE, tableTypeFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(COLS_COL_COLUMN_NAME, columnNameFilter) ); return exprNode != null ? new InfoSchemaFilter(exprNode) : null; } /** * Helper method to create {@link FunctionExprNode} from {@link LikeFilter}. * @param fieldName Name of the filed on which the like expression is applied. * @param likeFilter * @return {@link FunctionExprNode} for given arguments. Null if the likeFilter is null. */ private static FunctionExprNode createLikeFunctionExprNode(String fieldName, LikeFilter likeFilter) { if (likeFilter == null) { return null; } return new FunctionExprNode(LIKE_FUNCTION, likeFilter.hasEscape() ? ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern()), new ConstantExprNode(likeFilter.getEscape())) : ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern())) ); } /** * Helper method to create {@link FunctionExprNode} from {@code List}. * @param fieldName Name of the filed on which the like expression is applied. * @param valuesFilter a list of values * @return {@link FunctionExprNode} for given arguments. Null if the valuesFilter is null. */ private static FunctionExprNode createInFunctionExprNode(String fieldName, List valuesFilter) { if (valuesFilter == null) { return null; } ImmutableList.Builder nodes = ImmutableList.builder(); nodes.add(new FieldExprNode(fieldName)); for(String type: valuesFilter) { nodes.add(new ConstantExprNode(type)); } return new FunctionExprNode(IN_FUNCTION, nodes.build()); } /** * Helper method to combine two {@link FunctionExprNode}s with a given functionName. If one of them is * null, other one is returned as it is. */ private static FunctionExprNode combineFunctions(final String functionName, final FunctionExprNode func1, final FunctionExprNode func2) { if (func1 == null) { return func2; } if (func2 == null) { return func1; } return new FunctionExprNode(functionName, ImmutableList.of(func1, func2)); } /** * Helper method to create a {@link PojoRecordReader} for given arguments. * @param tableType * @param filter * @param provider * @param userSession * @return */ private static PojoRecordReader getPojoRecordReader(final InfoSchemaTableType tableType, final InfoSchemaFilter filter, final DrillConfig config, final SchemaTreeProvider provider, final UserSession userSession) { final SchemaPlus rootSchema = provider.createFullRootSchema(userSession.getCredentials().getUserName(), newSchemaConfigInfoProvider(config, userSession, provider)); return tableType.getRecordReader(rootSchema, filter, userSession.getOptions()); } /** * Helper method to create a {@link SchemaConfigInfoProvider} instance for metadata purposes. * @param session * @param schemaTreeProvider * @return */ private static SchemaConfigInfoProvider newSchemaConfigInfoProvider(final DrillConfig config, final UserSession session, final SchemaTreeProvider schemaTreeProvider) { return new SchemaConfigInfoProvider() { private final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(config, this); @Override public ViewExpansionContext getViewExpansionContext() { return viewExpansionContext; } @Override public SchemaPlus getRootSchema(String userName) { return schemaTreeProvider.createRootSchema(userName, this); } @Override public OptionValue getOption(String optionKey) { return session.getOptions().getOption(optionKey); } @Override public String getQueryUserName() { return session.getCredentials().getUserName(); } }; } /** * Helper method to create {@link DrillPBError} for client response message. * @param failedFunction Brief description of the failed function. * @param ex Exception thrown * @return */ static DrillPBError createPBError(final String failedFunction, final Throwable ex) { final String errorId = UUID.randomUUID().toString(); logger.error("Failed to {}. ErrorId: {}", failedFunction, errorId, ex); final DrillPBError.Builder builder = DrillPBError.newBuilder(); builder.setErrorType(ErrorType.SYSTEM); // Metadata requests shouldn't cause any user errors builder.setErrorId(errorId); if (ex.getMessage() != null) { builder.setMessage(ex.getMessage()); } builder.setException(ErrorHelper.getWrapper(ex)); return builder.build(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12709 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/work/metadata/MetadataProvider.java/#L84-L621 | 2 | 2000 | 12709 | critical |
| 3612 | { "message": "YES I found bad smells", "the bad smells are": ["Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | blob | t | t | f | blob | data class | 0 | 8077 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 1 | 3612 | 8077 | critical |
| 5709 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | f | f | f | long method | 0 | 12658 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5709 | 12658 | critical | ||
| 3371 | { "output": "YES I found bad smells the bad smells are: 1. Long method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
blob | Long method" } | t | f | f | . Long method" } | blob | 0 | 6412 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 1 | 3371 | 6412 | major |
| 98 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1293 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 2 | 98 | 1293 | minor |
| 2283 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Primitive Obsession 4. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Long Method2 Feature Envy3 Primitive Obsession4 Inappropriate Intimacy | t | f | f | . Long Method2. Feature Envy3. Primitive Obsession4. Inappropriate Intimacy | data class | 0 | 13842 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 2283 | 13842 | major |
| 824 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ArrayMap extends AbstractMap { private Object[] table; private int size; protected transient Collection values; public ArrayMap() { this(32); } public ArrayMap(int capacity) { table = new Object[capacity * 2]; size = 0; } @Override @SuppressWarnings("unchecked") public V get(Object key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } return null; } @Override @SuppressWarnings("unchecked") public V put(K key, V value) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { V old = (V) table[i + 1]; table[i + 1] = value; return old; } } if (size * 2 == table.length) { Object[] n = new Object[table.length * 2]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = value; return null; } @SuppressWarnings("unchecked") public V getOrCompute(K key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } V v = compute(key); if (size << 1 == table.length) { Object[] n = new Object[table.length << 1]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = v; return v; } protected V compute(K key) { throw new UnsupportedOperationException(); } @Override public Collection values() { if (values == null) { values = new AbstractCollection() { @Override public Iterator iterator() { return new Iterator() { int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public V next() { if (index >= size) { throw new NoSuchElementException(); } return (V) table[(index++ << 1) + 1]; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } return values; } @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { FastEntry entry = new FastEntry(); int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public FastEntry next() { if (index >= size) { throw new NoSuchElementException(); } int i = index << 1; entry.key = (K) table[i]; entry.value = (V) table[i + 1]; index++; return entry; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } static class FastEntry implements Entry { K key; V value; public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 7711 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/resolver/src/main/java/org/apache/felix/resolver/util/ArrayMap.java/#L23-L184 | 1 | 824 | 7711 | minor |
| 5107 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Complex code structure", "Data class", "Duplicated code", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } } |
blob | long method, complex code structure, data class, duplicated code, feature envy | t | t | f | long method, complex code structure, data class, duplicated code, feature envy | blob | 0 | 14309 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 | 2 | 5107 | 14309 | minor |
| 2462 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14549 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 1 | 2462 | 14549 | minor |
| 2437 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 14471 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 | 1 | 2437 | 14471 | major |
| 1565 | YES I found bad smells I found the following bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11326 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 1565 | 11326 | minor |
| 2384 | YES I found bad smells. The bad smells are: 1.Long method 2.Missing JavaDoc 3.Magic numbers 4.Large class 5.Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
blob | Long method2Missing JavaDoc3Magic numbers4Large class5Data class | t | f | f | .Long method2.Missing JavaDoc3.Magic numbers4.Large class5.Data class | blob | 0 | 14343 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 2 | 2384 | 14343 | minor |
| 2125 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 13220 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 2 | 2125 | 13220 | major |
| 5274 | I found bad smells. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14746 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5274 | 14746 | minor | ||
| 814 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 7656 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 2 | 814 | 7656 | critical |
| 857 | , I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7892 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L20095-L20123 | 2 | 857 | 7892 | minor | ||
| 2429 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextListenerStartup implements ServletContextListener { /** Configuration file path parameter name. */ public static final String IGNITE_CFG_FILE_PATH_PARAM = "IgniteConfigurationFilePath"; /** Names of started Ignite instances. */ private final Collection igniteInstanceNames = new ArrayList<>(); /** {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent evt) { ServletContext ctx = evt.getServletContext(); String cfgFile = ctx.getInitParameter(IGNITE_CFG_FILE_PATH_PARAM); Collection cfgs; GridSpringResourceContext rsrcCtx = null; if (cfgFile != null) { URL cfgUrl = null; try { cfgUrl = evt.getServletContext().getResource("/META-INF/" + cfgFile); } catch (MalformedURLException ignored) { // Ignore, we still need to try with IGNITE_HOME. } if (cfgUrl == null) // Try with IGNITE_HOME and with context class loader. cfgUrl = U.resolveIgniteUrl(cfgFile); if (cfgUrl == null) throw new IgniteException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile); IgniteBiTuple, ? extends GridSpringResourceContext> t; try { t = IgnitionEx.loadConfigurations(cfgUrl); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to load Ignite configuration.", e); } cfgs = t.get1(); rsrcCtx = t.get2(); if (cfgs.isEmpty()) throw new IgniteException("Can't find grid factory configuration in: " + cfgUrl); } else cfgs = Collections.singleton(new IgniteConfiguration()); try { assert !cfgs.isEmpty(); for (IgniteConfiguration cfg : cfgs) { assert cfg != null; Ignite ignite; synchronized (ServletContextListenerStartup.class) { try { ignite = G.ignite(cfg.getIgniteInstanceName()); } catch (IgniteIllegalStateException ignored) { ignite = IgnitionEx.start(new IgniteConfiguration(cfg), rsrcCtx); } } // Check if grid is not null - started properly. if (ignite != null) igniteInstanceNames.add(ignite.name()); } } catch (IgniteCheckedException e) { // Stop started grids only. for (String name : igniteInstanceNames) G.stop(name, true); throw new IgniteException("Failed to start Ignite.", e); } } /** {@inheritDoc} */ @Override public void contextDestroyed(ServletContextEvent evt) { // Stop started grids only. for (String name: igniteInstanceNames) G.stop(name, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ServletContextListenerStartup.class, this); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14453 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/web/src/main/java/org/apache/ignite/startup/servlet/ServletContextListenerStartup.java/#L95-L189 | 2 | 2429 | 14453 | minor |
| 320 | YES I found bad smells the bad smells are: 1. Feature envy - this class appears to be too focused on a specific type of data (i.e. columns and families) and may not be reusable or extensible for other purposes. 2. Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities. 3. Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation. 4. Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Feature envy - this class appears to be too focused on a specific type of data (ie columns and families) and may not be reusable or extensible for other purposes2 Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities3 Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation4 Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument | t | f | f | . Feature envy - this class appears to be too focused on a specific type of data (i.e. columns and families) and may not be reusable or extensible for other purposes.2. Long method - the constructor and equals() method are relatively long, potentially indicating that this class is trying to handle multiple responsibilities.3. Lack of encapsulation - the fields regionInfo and familySet are public, which could lead to unintended data manipulation.4. Possible null pointer exception - the equals() method does not check for null values, which could result in an error if a null value is passed in as an argument. | data class | 0 | 3293 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 320 | 3293 | minor |
| 193 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 2220 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 193 | 2220 | minor |
| 1118 | YES I found bad smells -the bad smells are: 1. Commented out code (lines 51-61) 2. Long method (lines 1-74) 3. Repeated code (lines 17-31 and lines 34-47) 4. Use of a "catch-all" Exception handler (line 18) 5. Conditional complexity (lines 17-47) 6. Method with multiple responsibilities (lines 1-74) 7. Inconsistent naming conventions for variables and methods (e.g. regionOrigin and regionExtent) 8. Magic numbers (lines 67 and 74) 9. Lack of proper error handling (e.g. returning null instead of throwing an exception) 10. Use of deprecated methods (e.g. Util.toLowerInvariant on line 65) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Commented out code (lines 5 | t | f | f | . Commented out code (lines 5 | long method | 0 | 9959 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1118 | 9959 | critical |
| 807 | {"output": "YES I found bad smells the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7626 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 807 | 7626 | minor |
| 79 | {"message": "YES I found bad smells", "bad smells are": [ "1. Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private final static class DuplicatableProgressTrackingInputStream extends ProgressTrackingInputStream implements DuplicatableInputStream { private DuplicatableProgressTrackingInputStream( final InputStream source, final ProgressTracker progressTracker) { super(source, progressTracker); if (!(source instanceof DuplicatableInputStream)) { throw new IllegalStateException("Source MUST be a DuplicatableInputStream"); } } /** * The progress tracking input stream resulting from this call will re-use the progress tracker from the parent * progress tracking input stream after resetting it, thus invalidating the progress tracked by the parent * stream until now. To ensure correctness of the progress tracking functionality, do NOT read from the parent * stream after duplicating from it. * @return The duplicated progress tracking input stream. */ @Override public InputStream duplicate() { return ProgressTrackingInputStreamFactory.create( ((DuplicatableInputStream) getSource()).duplicate(), getProgressTracker().reset()); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1169 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-extensions/src/main/java/com/oracle/bmc/objectstorage/transfer/ProgressTrackingInputStreamFactory.java/#L95-L120 | 2 | 79 | 1169 | minor |
| 1910 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12398 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 1 | 1910 | 12398 | minor |
| 983 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 8862 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 2 | 983 | 8862 | minor |
| 4314 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11368 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 4314 | 11368 | minor |
| 1167 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10186 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 | 2 | 1167 | 10186 | minor |
| 1104 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FunctionTagsTable extends Composite { private final FunctionEditorInput functionEditorInput; private final KeyValueSetEditingComposite tagsEditingComposite; private final KeyValueSetDataModel tagsDataModel; public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) { super(parent, SWT.NONE); this.functionEditorInput = functionEditorInput; this.setLayout(new GridLayout()); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList()); tagsEditingComposite = new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH))) .addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH))) .addKeyValidator(new LambdaTagNameValidator()) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSaveTags(); } }) .build(this, tagsDataModel); Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttonComposite.setLayout(new GridLayout(1, false)); refresh(); } public void refresh() { Map tagMap = functionEditorInput.getLambdaClient() .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); tagsDataModel.getPairSet().clear(); for (Entry entry : tagMap.entrySet()) { tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue())); } tagsEditingComposite.refresh(); } private void onSaveTags() { try { AWSLambda lambda = functionEditorInput.getLambdaClient(); Map oldTagMap = lambda .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); List tagKeysToBeRemoved = new ArrayList<>(); for (String key : oldTagMap.keySet()) { if (!tagsDataModel.getPairSet().contains(key)) { tagKeysToBeRemoved.add(key); } } Map tagMap = new HashMap<>(); for (Pair pair : tagsDataModel.getPairSet()) { tagMap.put(pair.getKey(), pair.getValue()); } if (!tagKeysToBeRemoved.isEmpty()) { lambda.untagResource(new UntagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTagKeys(tagKeysToBeRemoved)); } lambda.tagResource(new TagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTags(tagMap)); } catch (AWSLambdaException e) { LambdaPlugin.getDefault().reportException(e.getMessage(), e); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9849 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.java/#L47-L123 | 2 | 1104 | 9849 | minor |
| 2365 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14259 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 1 | 2365 | 14259 | minor |
| 1632 | YES I found bad smells the bad smells are: 1. SuppressWarnings 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | SuppressWarnings2 Long method | t | f | f | . SuppressWarnings2. Long method | data class | 0 | 11512 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 1632 | 11512 | minor |
| 2159 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13318 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 2 | 2159 | 13318 | critical |
| 1880 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | f | f | f | long method | 0 | 12284 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 1880 | 12284 | major | ||
| 3117 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JpaEntityFactoryMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String INDEX_VAR = "index"; private static final JavaSymbolName INDEX_SYMBOL = new JavaSymbolName(INDEX_VAR); private static final JavaSymbolName MAX_SYMBOL = new JavaSymbolName("max"); private static final JavaSymbolName MIN_SYMBOL = new JavaSymbolName("min"); private static final String OBJ_VAR = "obj"; private static final JavaSymbolName OBJ_SYMBOL = new JavaSymbolName(OBJ_VAR); private static final JavaSymbolName VALUE = new JavaSymbolName("value"); private static final JavaSymbolName CREATE_FACTORY_METHOD_NAME = new JavaSymbolName("create"); public static final JavaSymbolName SPECIFIC_METHOD_PREFIX = new JavaSymbolName("getSpecific"); private static final String PROVIDES_TYPE_STRING = JpaEntityFactoryMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); public static String createIdentifier(final JavaType javaType, final LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static String createIdentifier(ClassOrInterfaceTypeDetails details) { final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(details.getDeclaredByMetadataId()); return createIdentifier(details.getType(), logicalPath); } public static JavaType getJavaType(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static LogicalPath getPath(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } private JavaType entity; private final List requiredDataOnDemandCollaborators = new ArrayList(); private MethodMetadata randomPersistentEntityMethod; private final Map> embeddedFieldInitializers = new LinkedHashMap>(); private final Map fieldInitializers = new LinkedHashMap(); private EmbeddedIdHolder embeddedIdHolder; private List embeddedHolders; private Map locatedFields; private final MemberDetails entityMemberDetails; /** * Constructor * * @param identifier * @param aspectName * @param governorPhysicalTypeMetadata * @param entity * @param entityMemberDetails * @param locatedFields * @param embeddedHolder * @param entityFactoryClasses * @param embeddedIdHolder */ public JpaEntityFactoryMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JavaType entity, MemberDetails entityMemberDetails, final Map locatedFields, final List embeddedHolders, Set entityFactoryClasses, final EmbeddedIdHolder embeddedIdHolder) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.notNull(locatedFields, "Located fields map required"); Validate.notNull(embeddedHolders, "Embedded holders list required"); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.embeddedIdHolder = embeddedIdHolder; this.embeddedHolders = embeddedHolders; this.locatedFields = locatedFields; builder.addMethod(getCreateMethod()); // Calculate and store field initializers for (final Map.Entry entry : locatedFields.entrySet()) { final FieldMetadata field = entry.getKey(); final String initializer = getFieldInitializer(field, entry.getValue(), entityFactoryClasses); if (!StringUtils.isBlank(initializer)) { this.fieldInitializers.put(field, initializer); } } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { final Map initializers = new LinkedHashMap(); for (final FieldMetadata field : embeddedHolder.getFields()) { initializers.put(field, getFieldInitializer(field, null, entityFactoryClasses)); } this.embeddedFieldInitializers.put(embeddedHolder.getEmbeddedField(), initializers); } for (final EmbeddedHolder embeddedHolder : embeddedHolders) { builder.addMethod(getEmbeddedClassMutatorMethod(embeddedHolder)); addEmbeddedClassFieldMutatorMethodsToBuilder(embeddedHolder, entityFactoryClasses); } for (final MethodMetadataBuilder fieldInitializerMethod : getFieldMutatorMethods()) { builder.addMethod(fieldInitializerMethod); } addCollaboratingFieldsToBuilder(entityFactoryClasses); builder.addMethod(getEmbeddedIdMutatorMethod(entityFactoryClasses)); itdTypeDetails = builder.build(); } private void addCollaboratingFieldsToBuilder( final Set entityFactoryClasses) { final Set fields = new LinkedHashSet(); for (final JavaType entityNeedingCollaborator : this.requiredDataOnDemandCollaborators) { final JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator, entityFactoryClasses); if (collaboratorType != null) { final String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator, entityFactoryClasses) .getSymbolName(); final JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // We really expect the field to be correct if we're going to // rely on it Validate .isTrue(candidate.getFieldType().equals(collaboratorType), "Field '%s' on '%s' must be of type '%s'", collaboratingFieldName, destination.getFullyQualifiedTypeName(), collaboratorType.getFullyQualifiedTypeName()); Validate.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '%s' on '%s' must be private", collaboratingFieldName, destination.getFullyQualifiedTypeName()); Validate.notNull( MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), AUTOWIRED), "Field '%s' on '%s' must be @Autowired", collaboratingFieldName, destination.getFullyQualifiedTypeName()); // It's ok, so we can move onto the new field continue; } // Create field and add it to the ITD, if it hasn't already been if (!fields.contains(fieldSymbolName)) { // Must make the field final List annotations = new ArrayList(); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); builder.addField(new FieldMetadataBuilder(getId(), 0, annotations, fieldSymbolName, collaboratorType)); fields.add(fieldSymbolName); } } } } private void addEmbeddedClassFieldMutatorMethodsToBuilder(final EmbeddedHolder embeddedHolder, final Set dataOnDemandClasses) { final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); final JavaType[] parameterTypes = {embeddedFieldType, JavaType.INT_PRIMITIVE}; final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); for (final FieldMetadata field : embeddedHolder.getFields()) { final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); final JavaSymbolName fieldMutatorMethodName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, fieldMutatorMethodName, false)); final JavaSymbolName embeddedClassMethodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()); if (governorHasMethod(embeddedClassMethodName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } builder.addMethod(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, embeddedClassMethodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType .convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } private String getColumnPrecisionAndScaleBody(final FieldMetadata field, final Map values, final String suffix) { if (values == null || !values.containsKey("precision")) { return InvocableMemberBodyBuilder.getInstance().getOutput(); } final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); Integer precision = (Integer) values.get("precision"); Integer scale = (Integer) values.get("scale"); if (precision != null && scale != null && precision < scale) { scale = 0; } final BigDecimal maxValue; if (scale == null || scale == 0) { maxValue = new BigDecimal(StringUtils.rightPad("9", precision, '9')); } else { maxValue = new BigDecimal(StringUtils.rightPad("9", precision - scale, '9') + "." + StringUtils.rightPad("9", scale, '9')); } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private JavaSymbolName getCollaboratingFieldName(final JavaType entity, final Set dataOnDemandClasses) { JavaSymbolName symbolName = null; JavaType collaboratingType = getCollaboratingType(entity, dataOnDemandClasses); if (collaboratingType != null) { symbolName = new JavaSymbolName(StringUtils.uncapitalize(collaboratingType.getSimpleTypeName())); } return symbolName; } private JavaType getCollaboratingType(final JavaType entity, final Set entityFactoryClasses) { JavaType dataOnDemand = null; for (ClassOrInterfaceTypeDetails dataOnDemandClass : entityFactoryClasses) { String searchDataOnDemand = entity.getSimpleTypeName().concat("DataOnDemand"); if (dataOnDemandClass.getType().getSimpleTypeName().equals(searchDataOnDemand) && governorTypeDetails.getType().getModule() .equals(dataOnDemandClass.getType().getModule())) { dataOnDemand = dataOnDemandClass.getType(); } } return dataOnDemand; } private MethodMetadata getCreateMethod() { // Define methodName final JavaSymbolName methodName = CREATE_FACTORY_METHOD_NAME; List parameterTypes = new ArrayList(); parameterTypes.add(JavaType.INT_PRIMITIVE); // Check if method exists MethodMetadata existingMethod = getGovernorMethod(methodName, parameterTypes); if (existingMethod != null) { return existingMethod; } List parameterNames = new ArrayList(); parameterNames.add(INDEX_SYMBOL); // Add body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); List constructors = entityMemberDetails.getConstructors(); boolean hasDefaultConstructor = false; for (ConstructorMetadata constructor : constructors) { if (constructor.getParameterTypes().isEmpty() && Modifier.isPublic(constructor.getModifier())) { hasDefaultConstructor = true; break; } } if (constructors.isEmpty() || hasDefaultConstructor) { generateDefaultCreateMethodBody(bodyBuilder); } else { generateNoConstructorCreateMethodBody(bodyBuilder); } // Create method MethodMetadataBuilder method = new MethodMetadataBuilder(this.getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); CommentStructure commentStructure = new CommentStructure(); List paramsInfo = new ArrayList(); paramsInfo.add(String.format("%s position of the %s", INDEX_VAR, this.entity.getSimpleTypeName())); JavadocComment comment = new JavadocComment(String.format("Creates a new {@link %s} with the given %s.", this.entity.getSimpleTypeName(), INDEX_VAR), paramsInfo, String.format( "a new transient %s", this.entity.getSimpleTypeName()), null); commentStructure.addComment(comment, CommentLocation.BEGINNING); method.setCommentStructure(commentStructure); return method.build(); } /** * Generate default body for create method * * @param bodyBuilder */ private void generateDefaultCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // Entity obj = new Entity(); bodyBuilder.appendFormalLine("%1$s %2$s = new %1$s();", getNameOfJavaType(this.entity), OBJ_SYMBOL); // Set values for transient object for (final Map.Entry entry : locatedFields.entrySet()) { bodyBuilder.appendFormalLine("%s(%s, %s);", BeanInfoUtils.getMutatorMethodName(entry.getKey()), OBJ_SYMBOL, INDEX_SYMBOL); } // return obj; bodyBuilder.appendFormalLine("return %s;", OBJ_SYMBOL); } /** * Generate body for create method when entity has not default constructor available * * @param bodyBuilder */ private void generateNoConstructorCreateMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // throw new IllegalStateException("No no-argument constructor found for the entity "+ Pet.class.getName() +". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again."); bodyBuilder .appendFormalLine( "throw new IllegalStateException(\"No no-argument constructor found for the entity \"+ %s.class.getName() +\". This is required by the JPA especification. Please provide a default constructor for the related class and open the Spring Roo console again.\");", getNameOfJavaType(this.entity)); } private String getDecimalMinAndDecimalMaxBody(final FieldMetadata field, final AnnotationMetadata decimalMinAnnotation, final AnnotationMetadata decimalMaxAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (decimalMinAnnotation != null && decimalMaxAnnotation == null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation == null && decimalMaxAnnotation != null) { final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (decimalMinAnnotation != null && decimalMaxAnnotation != null) { final String minValue = (String) decimalMinAnnotation.getAttribute(VALUE).getValue(); final String maxValue = (String) decimalMaxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue( Double.parseDouble(maxValue) >= Double.parseDouble(minValue), "The value of @DecimalMax must be greater or equal to the value of @DecimalMin for field %s", fieldName); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getDigitsBody(final FieldMetadata field, final AnnotationMetadata digitsAnnotation, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final Integer integerValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("integer")).getValue(); final Integer fractionValue = (Integer) digitsAnnotation.getAttribute(new JavaSymbolName("fraction")).getValue(); final BigDecimal maxValue = new BigDecimal(StringUtils.rightPad("9", integerValue, '9') + "." + StringUtils.rightPad("9", fractionValue, '9')); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (fieldType.equals(BIG_DECIMAL)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_DECIMAL.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue.doubleValue() + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue.doubleValue() + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); return bodyBuilder.getOutput(); } private String getFieldInitializer(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set dataOnDemandClasses) { final JavaType fieldType = field.getFieldType(); final String fieldName = field.getFieldName().getSymbolName(); String initializer = "null"; final String fieldInitializer = field.getFieldInitializer(); final Set fieldCustomDataKeys = field.getCustomData().keySet(); // Date fields included for DataNucleus ( if (fieldType.equals(DATE)) { if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() - 10000000L)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { builder.getImportRegistrationResolver().addImport(DATE); initializer = "new Date(new Date().getTime() + 10000000L)"; } else { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); initializer = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime()"; } } else if (fieldType.equals(CALENDAR)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR); final String calendarString = "new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH)"; if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) { initializer = calendarString + " - 1)"; } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) { initializer = calendarString + " + 1)"; } else { initializer = "Calendar.getInstance()"; } } else if (fieldType.equals(TIMESTAMP)) { builder.getImportRegistrationResolver().addImports(CALENDAR, GREGORIAN_CALENDAR, TIMESTAMP); initializer = "new Timestamp(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), \n\t\t\tCalendar.getInstance().get(Calendar.MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.DAY_OF_MONTH), \n\t\t\tCalendar.getInstance().get(Calendar.HOUR_OF_DAY), \n\t\t\tCalendar.getInstance().get(Calendar.MINUTE), \n\t\t\tCalendar.getInstance().get(Calendar.SECOND) + \n\t\t\tnew Double(Math.random() * 1000).intValue()).getTime().getTime())"; } else if (fieldType.equals(STRING)) { if (fieldInitializer != null && fieldInitializer.contains("\"")) { final int offset = fieldInitializer.indexOf("\""); initializer = fieldInitializer.substring(offset + 1, fieldInitializer.lastIndexOf("\"")); } else { initializer = fieldName; } if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), VALIDATOR_CONSTRAINTS_EMAIL) != null || fieldName.toLowerCase().contains("email")) { initializer = "\"foo\" + " + INDEX_VAR + " + \"@bar.com\""; } else { int maxLength = Integer.MAX_VALUE; // Check for @Size final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null) { final AnnotationAttributeValue maxValue = sizeAnnotation.getAttribute(MAX_SYMBOL); if (maxValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "max", maxValue.getValue()); maxLength = ((Integer) maxValue.getValue()).intValue(); } final AnnotationAttributeValue minValue = sizeAnnotation.getAttribute(MIN_SYMBOL); if (minValue != null) { validateNumericAnnotationAttribute(fieldName, "@Size", "min", minValue.getValue()); final int minLength = ((Integer) minValue.getValue()).intValue(); Validate.isTrue(maxLength >= minLength, "@Size attribute 'max' must be greater than 'min' for field '%s' in %s", fieldName, entity.getFullyQualifiedTypeName()); if (initializer.length() + 2 < minLength) { initializer = String.format("%1$-" + (minLength - 2) + "s", initializer).replace(' ', 'x'); } } } else { if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map columnValues = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (columnValues.keySet().contains("length")) { final Object lengthValue = columnValues.get("length"); validateNumericAnnotationAttribute(fieldName, "@Column", "length", lengthValue); maxLength = ((Integer) lengthValue).intValue(); } } } switch (maxLength) { case 0: initializer = "\"\""; break; case 1: initializer = "String.valueOf(" + INDEX_VAR + ")"; break; case 2: initializer = "\"" + initializer.charAt(0) + "\" + " + INDEX_VAR; break; default: if (initializer.length() + 2 > maxLength) { initializer = "\"" + initializer.substring(0, maxLength - 2) + "_\" + " + INDEX_VAR; } else { initializer = "\"" + initializer + "_\" + " + INDEX_VAR; } } } } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ \"Y\", \"N\" }"); } else if (fieldType.equals(JavaType.BOOLEAN_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "Boolean.TRUE"); } else if (fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "true"); } else if (fieldType.equals(JavaType.INT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ")"); } else if (fieldType.equals(JavaType.INT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, INDEX_VAR); } else if (fieldType.equals(new JavaType(JavaType.INT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ " + INDEX_VAR + ", " + INDEX_VAR + " }"); } else if (fieldType.equals(JavaType.DOUBLE_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").doubleValue()"); } else if (fieldType.equals(new JavaType(JavaType.DOUBLE_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").doubleValue(), new Integer(" + INDEX_VAR + ").doubleValue() }"); } else if (fieldType.equals(JavaType.FLOAT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").floatValue()"); } else if (fieldType.equals(new JavaType(JavaType.FLOAT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").floatValue(), new Integer(" + INDEX_VAR + ").floatValue() }"); } else if (fieldType.equals(JavaType.LONG_OBJECT)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.LONG_PRIMITIVE)) { initializer = StringUtils .defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").longValue()"); } else if (fieldType.equals(new JavaType(JavaType.LONG_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").longValue(), new Integer(" + INDEX_VAR + ").longValue() }"); } else if (fieldType.equals(JavaType.SHORT_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); // Auto-boxed } else if (fieldType.equals(JavaType.SHORT_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Integer(" + INDEX_VAR + ").shortValue()"); } else if (fieldType.equals(new JavaType(JavaType.SHORT_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ new Integer(" + INDEX_VAR + ").shortValue(), new Integer(" + INDEX_VAR + ").shortValue() }"); } else if (fieldType.equals(JavaType.CHAR_OBJECT)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "new Character('N')"); } else if (fieldType.equals(JavaType.CHAR_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "'N'"); } else if (fieldType.equals(new JavaType(JavaType.CHAR_OBJECT.getFullyQualifiedTypeName(), 1, DataType.PRIMITIVE, null, null))) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "{ 'Y', 'N' }"); } else if (fieldType.equals(BIG_DECIMAL)) { builder.getImportRegistrationResolver().addImport(BIG_DECIMAL); initializer = BIG_DECIMAL.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(BIG_INTEGER)) { builder.getImportRegistrationResolver().addImport(BIG_INTEGER); initializer = BIG_INTEGER.getSimpleTypeName() + ".valueOf(" + INDEX_VAR + ")"; } else if (fieldType.equals(JavaType.BYTE_OBJECT)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ")"; } else if (fieldType.equals(JavaType.BYTE_PRIMITIVE)) { initializer = "new Byte(" + StringUtils.defaultIfEmpty(fieldInitializer, "\"1\"") + ").byteValue()"; } else if (fieldType.equals(JavaType.BYTE_ARRAY_PRIMITIVE)) { initializer = StringUtils.defaultIfEmpty(fieldInitializer, "String.valueOf(" + INDEX_VAR + ").getBytes()"); } else if (fieldType.equals(entity)) { // Avoid circular references (ROO-562) initializer = OBJ_VAR; } else if (fieldCustomDataKeys.contains(CustomDataKeys.ENUMERATED_FIELD)) { builder.getImportRegistrationResolver().addImport(fieldType); initializer = fieldType.getSimpleTypeName() + ".class.getEnumConstants()[0]"; } else if (collaboratingMetadata != null && collaboratingMetadata.getEntityType() != null) { requiredDataOnDemandCollaborators.add(fieldType); initializer = getFieldInitializerForRelatedEntity(field, collaboratingMetadata, fieldCustomDataKeys, dataOnDemandClasses); } return initializer; } private String getFieldInitializerForRelatedEntity(final FieldMetadata field, final JpaEntityFactoryMetadata collaboratingMetadata, final Set fieldCustomDataKeys, final Set dataOnDemandClasses) { // To avoid circular references, we don't try to set nullable fields final boolean nullableField = field.getAnnotation(NOT_NULL) == null && isNullableJoinColumn(field); if (nullableField) { return null; } JavaSymbolName collaboratingFieldName = getCollaboratingFieldName(field.getFieldType(), dataOnDemandClasses); if (collaboratingFieldName != null) { final String collaboratingName = collaboratingFieldName.getSymbolName(); if (fieldCustomDataKeys.contains(CustomDataKeys.ONE_TO_ONE_FIELD)) { // We try to keep the same ID (ROO-568) return collaboratingName + "." + SPECIFIC_METHOD_PREFIX.getSymbolName() + "(" + INDEX_VAR + ")"; } return collaboratingName + "." + collaboratingMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()"; } else { return null; } } private List getFieldMutatorMethods() { final List fieldMutatorMethods = new ArrayList(); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; for (final Map.Entry entry : fieldInitializers.entrySet()) { final FieldMetadata field = entry.getKey(); final JavaSymbolName mutatorName = BeanInfoUtils.getMutatorMethodName(field.getFieldName()); // Locate user-defined method if (governorHasMethod(mutatorName, parameterTypes)) { // Method found in governor so do not create method in ITD continue; } // Method not on governor so need to create it final String initializer = entry.getValue(); if (!StringUtils.isBlank(initializer)) { final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.append(getFieldValidationBody(field, initializer, mutatorName, false)); fieldMutatorMethods.add(new MethodMetadataBuilder(getId(), Modifier.PUBLIC, mutatorName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder)); } } return fieldMutatorMethods; } private String getFieldValidationBody(final FieldMetadata field, final String initializer, final JavaSymbolName mutatorName, final boolean isFieldOfEmbeddableType) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); String suffix = ""; if (fieldType.equals(JavaType.LONG_OBJECT) || fieldType.equals(JavaType.LONG_PRIMITIVE)) { suffix = "L"; } else if (fieldType.equals(JavaType.FLOAT_OBJECT) || fieldType.equals(JavaType.FLOAT_PRIMITIVE)) { suffix = "F"; } else if (fieldType.equals(JavaType.DOUBLE_OBJECT) || fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) { suffix = "D"; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(getTypeStr(fieldType) + " " + fieldName + " = " + initializer + ";"); if (fieldType.equals(JavaType.STRING)) { boolean isUnique = isFieldOfEmbeddableType; @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); if (!isUnique && values != null && values.containsKey("unique")) { isUnique = (Boolean) values.get("unique"); } // Check for @Size or @Column with length attribute final AnnotationMetadata sizeAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE); if (sizeAnnotation != null && sizeAnnotation.getAttribute(MAX_SYMBOL) != null) { final Integer maxValue = (Integer) sizeAnnotation.getAttribute(MAX_SYMBOL).getValue(); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + maxValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + maxValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + maxValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (sizeAnnotation == null && values != null) { if (values.containsKey("length")) { final Integer lengthValue = (Integer) values.get("length"); bodyBuilder.appendFormalLine("if (" + fieldName + ".length() > " + lengthValue + ") {"); bodyBuilder.indent(); if (isUnique) { bodyBuilder.appendFormalLine(fieldName + " = new Random().nextInt(10) + " + fieldName + ".substring(1, " + lengthValue + ");"); } else { bodyBuilder.appendFormalLine(fieldName + " = " + fieldName + ".substring(0, " + lengthValue + ");"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } } else if (JdkJavaType.isDecimalType(fieldType)) { // Check for @Digits, @DecimalMax, @DecimalMin final AnnotationMetadata digitsAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DIGITS); final AnnotationMetadata decimalMinAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MIN); final AnnotationMetadata decimalMaxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DECIMAL_MAX); if (digitsAnnotation != null) { bodyBuilder.append(getDigitsBody(field, digitsAnnotation, suffix)); } else if (decimalMinAnnotation != null || decimalMaxAnnotation != null) { bodyBuilder.append(getDecimalMinAndDecimalMaxBody(field, decimalMinAnnotation, decimalMaxAnnotation, suffix)); } else if (field.getCustomData().keySet().contains(CustomDataKeys.COLUMN_FIELD)) { @SuppressWarnings("unchecked") final Map values = (Map) field.getCustomData().get(CustomDataKeys.COLUMN_FIELD); bodyBuilder.append(getColumnPrecisionAndScaleBody(field, values, suffix)); } } else if (JdkJavaType.isIntegerType(fieldType)) { // Check for @Min and @Max bodyBuilder.append(getMinAndMaxBody(field, suffix)); } if (mutatorName != null) { bodyBuilder.appendFormalLine(OBJ_VAR + "." + mutatorName.getSymbolName() + "(" + fieldName + ");"); } return bodyBuilder.getOutput(); } private MethodMetadataBuilder getEmbeddedClassMutatorMethod(final EmbeddedHolder embeddedHolder) { final JavaSymbolName methodName = getEmbeddedFieldMutatorMethodName(embeddedHolder.getEmbeddedField().getFieldName()); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded class final JavaType embeddedFieldType = embeddedHolder.getEmbeddedField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedFieldType); bodyBuilder.appendFormalLine(embeddedFieldType.getSimpleTypeName() + " embeddedClass = new " + embeddedFieldType.getSimpleTypeName() + "();"); for (final FieldMetadata field : embeddedHolder.getFields()) { bodyBuilder.appendFormalLine(getEmbeddedFieldMutatorMethodName( embeddedHolder.getEmbeddedField().getFieldName(), field.getFieldName()).getSymbolName() + "(embeddedClass, " + INDEX_VAR + ");"); } bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedHolder.getEmbeddedMutatorMethodName() + "(embeddedClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private MethodMetadataBuilder getEmbeddedIdMutatorMethod( final Set dataOnDemandClasses) { if (!hasEmbeddedIdentifier()) { return null; } final JavaSymbolName embeddedIdMutator = embeddedIdHolder.getEmbeddedIdMutator(); final JavaSymbolName methodName = getEmbeddedIdMutatorMethodName(); final JavaType[] parameterTypes = {entity, JavaType.INT_PRIMITIVE}; // Locate user-defined method if (governorHasMethod(methodName, parameterTypes)) { // Method found in governor so do not create method in ITD return null; } final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Create constructor for embedded id class final JavaType embeddedIdFieldType = embeddedIdHolder.getEmbeddedIdField().getFieldType(); builder.getImportRegistrationResolver().addImport(embeddedIdFieldType); final StringBuilder sb = new StringBuilder(); final List identifierFields = embeddedIdHolder.getIdFields(); for (int i = 0, n = identifierFields.size(); i < n; i++) { if (i > 0) { sb.append(", "); } final FieldMetadata field = identifierFields.get(i); final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); builder.getImportRegistrationResolver().addImport(fieldType); final String initializer = getFieldInitializer(field, null, dataOnDemandClasses); bodyBuilder.append(getFieldValidationBody(field, initializer, null, true)); sb.append(fieldName); } bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine(embeddedIdFieldType.getSimpleTypeName() + " embeddedIdClass = new " + embeddedIdFieldType.getSimpleTypeName() + "(" + sb.toString() + ");"); bodyBuilder.appendFormalLine(OBJ_VAR + "." + embeddedIdMutator + "(embeddedIdClass);"); final List parameterNames = Arrays.asList(OBJ_SYMBOL, INDEX_SYMBOL); return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder); } private String getMinAndMaxBody(final FieldMetadata field, final String suffix) { final String fieldName = field.getFieldName().getSymbolName(); final JavaType fieldType = field.getFieldType(); final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); final AnnotationMetadata minAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN); final AnnotationMetadata maxAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX); if (minAnnotation != null && maxAnnotation == null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + minValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation == null && maxAnnotation != null) { final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } else if (minAnnotation != null && maxAnnotation != null) { final Number minValue = (Number) minAnnotation.getAttribute(VALUE).getValue(); final Number maxValue = (Number) maxAnnotation.getAttribute(VALUE).getValue(); Validate .isTrue(maxValue.longValue() >= minValue.longValue(), "The value of @Max must be greater or equal to the value of @Min for field %s", fieldName); if (fieldType.equals(BIG_INTEGER)) { bodyBuilder.appendFormalLine("if (" + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + minValue + "\")) == -1 || " + fieldName + ".compareTo(new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\")) == 1) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = new " + BIG_INTEGER.getSimpleTypeName() + "(\"" + maxValue + "\");"); } else { bodyBuilder.appendFormalLine("if (" + fieldName + " < " + minValue + suffix + " || " + fieldName + " > " + maxValue + suffix + ") {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(fieldName + " = " + maxValue + suffix + ";"); } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } return bodyBuilder.getOutput(); } private String getTypeStr(final JavaType fieldType) { builder.getImportRegistrationResolver().addImport(fieldType); final String arrayStr = fieldType.isArray() ? "[]" : ""; String typeStr = fieldType.getSimpleTypeName(); if (fieldType.getFullyQualifiedTypeName().equals( JavaType.FLOAT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "float" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.DOUBLE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "double" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.INT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "int" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.SHORT_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "short" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.BYTE_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "byte" + arrayStr; } else if (fieldType.getFullyQualifiedTypeName().equals( JavaType.CHAR_PRIMITIVE.getFullyQualifiedTypeName()) && fieldType.isPrimitive()) { typeStr = "char" + arrayStr; } else if (fieldType.equals(new JavaType(STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null))) { typeStr = "String[]"; } return typeStr; } private boolean isNullableJoinColumn(final FieldMetadata field) { final AnnotationMetadata joinColumnAnnotation = field.getAnnotation(JOIN_COLUMN); if (joinColumnAnnotation == null) { return true; } final AnnotationAttributeValue nullableAttr = joinColumnAnnotation.getAttribute(new JavaSymbolName("nullable")); return nullableAttr == null || (Boolean) nullableAttr.getValue(); } private void validateNumericAnnotationAttribute(final String fieldName, final String annotationName, final String attributeName, final Object object) { Validate.isTrue(NumberUtils.isNumber(object.toString()), "%s '%s' attribute for field '%s' in backing type %s must be numeric", annotationName, attributeName, fieldName, entity.getFullyQualifiedTypeName()); } public JavaSymbolName getCreateFactoryMethodName() { return JpaEntityFactoryMetadata.CREATE_FACTORY_METHOD_NAME; } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName fieldName) { return BeanInfoUtils.getMutatorMethodName(fieldName); } public JavaSymbolName getEmbeddedFieldMutatorMethodName(final JavaSymbolName embeddedFieldName, final JavaSymbolName fieldName) { return getEmbeddedFieldMutatorMethodName(new JavaSymbolName(embeddedFieldName.getSymbolName() + StringUtils.capitalize(fieldName.getSymbolName()))); } public List getEmbeddedHolders() { return this.embeddedHolders; } public JavaSymbolName getEmbeddedIdMutatorMethodName() { final List fieldNames = new ArrayList(); for (final FieldMetadata field : fieldInitializers.keySet()) { fieldNames.add(field.getFieldName()); } int index = -1; JavaSymbolName embeddedIdField; while (true) { // Compute the required field name index++; embeddedIdField = new JavaSymbolName("embeddedIdClass" + StringUtils.repeat("_", index)); if (!fieldNames.contains(embeddedIdField)) { // Found a usable name break; } } return BeanInfoUtils.getMutatorMethodName(embeddedIdField); } public JavaType getEntityType() { return this.entity; } /** * Returns the {@link JavaType} representing the physical type of this ITD governor. * * @return the {@link JavaType} for the governor physical type. */ public JavaType getGovernorType() { return this.governorPhysicalTypeMetadata.getType(); } /** * @return the "getRandomEntity():Entity" method (never returns null) */ public MethodMetadata getRandomPersistentEntityMethod() { return randomPersistentEntityMethod; } public boolean hasEmbeddedIdentifier() { return this.embeddedIdHolder != null; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 4137 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadata.java/#L77-L1176 | 2 | 3117 | 4137 | major |
| 769 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Data class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 7259 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 1 | 769 | 7259 | minor |
| 1681 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11679 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 1 | 1681 | 11679 | minor |
| 3996 | {"response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JavadocFormatter { private static final String CODE_RESET = "\033[0m"; private static final String CODE_HIGHLIGHT = "\033[1m"; private static final String CODE_UNDERLINE = "\033[4m"; private final int lineLimit; private final boolean escapeSequencesSupported; /** Construct the formatter. * * @param lineLimit maximum line length * @param escapeSequencesSupported whether escape sequences are supported */ public JavadocFormatter(int lineLimit, boolean escapeSequencesSupported) { this.lineLimit = lineLimit; this.escapeSequencesSupported = escapeSequencesSupported; } private static final int MAX_LINE_LENGTH = 95; private static final int SHORTEST_LINE = 30; private static final int INDENT = 4; /**Format javadoc to plain text. * * @param header element caption that should be used * @param javadoc to format * @return javadoc formatted to plain text */ public String formatJavadoc(String header, String javadoc) { try { StringBuilder result = new StringBuilder(); result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n"); if (javadoc == null) { return result.toString(); } JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null); DocTrees trees = DocTrees.instance(task); DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) { @Override @DefinedBy(Api.COMPILER) public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "" + javadoc + ""; } }); new FormatJavadocScanner(result, task).scan(docComment, null); addNewLineIfNeeded(result); return result.toString(); } catch (URISyntaxException ex) { throw new InternalError("Unexpected exception", ex); } } private class FormatJavadocScanner extends DocTreeScanner { private final StringBuilder result; private final JavacTask task; private int reflownTo; private int indent; private int limit = Math.min(lineLimit, MAX_LINE_LENGTH); private boolean pre; private Map tableColumns; public FormatJavadocScanner(StringBuilder result, JavacTask task) { this.result = result; this.task = task; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitDocComment(DocCommentTree node, Object p) { tableColumns = countTableColumns(node); reflownTo = result.length(); scan(node.getFirstSentence(), p); scan(node.getBody(), p); reflow(result, reflownTo, indent, limit); for (Sections current : docSections.keySet()) { boolean seenAny = false; for (DocTree t : node.getBlockTags()) { if (current.matches(t)) { if (!seenAny) { seenAny = true; if (result.charAt(result.length() - 1) != '\n') result.append("\n"); result.append("\n"); result.append(escape(CODE_UNDERLINE)) .append(docSections.get(current)) .append(escape(CODE_RESET)) .append("\n"); } scan(t, null); } } } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitText(TextTree node, Object p) { String text = node.getBody(); if (!pre) { text = text.replaceAll("[ \t\r\n]+", " ").trim(); if (text.isEmpty()) { text = " "; } } else { text = text.replaceAll("\n", "\n" + indentString(indent)); } result.append(text); return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLink(LinkTree node, Object p) { if (!node.getLabel().isEmpty()) { scan(node.getLabel(), p); } else { result.append(node.getReference().getSignature()); } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitParam(ParamTree node, Object p) { return formatDef(node.getName().getName(), node.getDescription()); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitThrows(ThrowsTree node, Object p) { return formatDef(node.getExceptionName().getSignature(), node.getDescription()); } public Object formatDef(CharSequence name, List description) { result.append(name); result.append(" - "); reflownTo = result.length(); indent = name.length() + 3; if (limit - indent < SHORTEST_LINE) { result.append("\n"); result.append(indentString(INDENT)); indent = INDENT; reflownTo += INDENT; } try { return scan(description, null); } finally { reflow(result, reflownTo, indent, limit); result.append("\n"); } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLiteral(LiteralTree node, Object p) { return scan(node.getBody(), p); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitReturn(ReturnTree node, Object p) { reflownTo = result.length(); try { return super.visitReturn(node, p); } finally { reflow(result, reflownTo, 0, limit); } } Stack listStack = new Stack<>(); Stack defStack = new Stack<>(); Stack tableStack = new Stack<>(); Stack> cellsStack = new Stack<>(); Stack> headerStack = new Stack<>(); @Override @DefinedBy(Api.COMPILER_TREE) public Object visitStartElement(StartElementTree node, Object p) { switch (getHtmlTag(node.getName())) { case P: if (lastNode!= null && lastNode.getKind() == DocTree.Kind.START_ELEMENT && HtmlTag.get(((StartElementTree) lastNode).getName()) == HtmlTag.LI) { //ignore break; } reflowTillNow(); addNewLineIfNeeded(result); result.append(indentString(indent)); reflownTo = result.length(); break; case BLOCKQUOTE: reflowTillNow(); indent += INDENT; break; case PRE: reflowTillNow(); pre = true; break; case UL: reflowTillNow(); listStack.push(-1); indent += INDENT; break; case OL: reflowTillNow(); listStack.push(1); indent += INDENT; break; case DL: reflowTillNow(); defStack.push(indent); break; case LI: reflowTillNow(); if (!listStack.empty()) { addNewLineIfNeeded(result); int top = listStack.pop(); if (top == (-1)) { result.append(indentString(indent - 2)); result.append("* "); } else { result.append(indentString(indent - 3)); result.append("" + top++ + ". "); } listStack.push(top); reflownTo = result.length(); } break; case DT: reflowTillNow(); if (!defStack.isEmpty()) { addNewLineIfNeeded(result); indent = defStack.peek(); result.append(escape(CODE_HIGHLIGHT)); } break; case DD: reflowTillNow(); if (!defStack.isEmpty()) { if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } addNewLineIfNeeded(result); indent = defStack.peek() + INDENT; result.append(indentString(indent)); } break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); addNewLineIfNeeded(result); result.append("\n") .append(escape(CODE_UNDERLINE)); reflownTo = result.length(); break; case TABLE: int columns = tableColumns.get(node); if (columns == 0) { break; //broken input } reflowTillNow(); addNewLineIfNeeded(result); reflownTo = result.length(); tableStack.push(limit); limit = (limit - 1) / columns - 3; for (int sep = 0; sep < (limit + 3) * columns + 1; sep++) { result.append("-"); } result.append("\n"); break; case TR: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(node.getName()); } cellsStack.push(new ArrayList<>()); headerStack.push(new ArrayList<>()); break; case TH: case TD: if (cellsStack.isEmpty()) { //broken code break; } reflowTillNow(); result.append("\n"); reflownTo = result.length(); cellsStack.peek().add(result.length()); headerStack.peek().add(HtmlTag.get(node.getName()) == HtmlTag.TH); break; case IMG: for (DocTree attr : node.getAttributes()) { if (attr.getKind() != DocTree.Kind.ATTRIBUTE) { continue; } AttributeTree at = (AttributeTree) attr; if ("alt".equals(StringUtils.toLowerCase(at.getName().toString()))) { addSpaceIfNeeded(result); scan(at.getValue(), null); addSpaceIfNeeded(result); break; } } break; default: addSpaceIfNeeded(result); break; } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEndElement(EndElementTree node, Object p) { handleEndElement(node.getName()); return super.visitEndElement(node, p); } private void handleEndElement(Name name) { switch (getHtmlTag(name)) { case BLOCKQUOTE: indent -= INDENT; break; case PRE: pre = false; addNewLineIfNeeded(result); reflownTo = result.length(); break; case UL: case OL: if (listStack.isEmpty()) { //ignore stray closing tag break; } reflowTillNow(); listStack.pop(); indent -= INDENT; addNewLineIfNeeded(result); break; case DL: if (defStack.isEmpty()) {//ignore stray closing tag break; } reflowTillNow(); if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } indent = defStack.pop(); addNewLineIfNeeded(result); break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); result.append(escape(CODE_RESET)) .append("\n"); reflownTo = result.length(); break; case TABLE: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(task.getElements().getName("tr")); } if (tableStack.isEmpty()) { break; } limit = tableStack.pop(); break; case TR: if (cellsStack.isEmpty()) { break; } reflowTillNow(); List cells = cellsStack.pop(); List headerFlags = headerStack.pop(); List content = new ArrayList<>(); int maxLines = 0; result.append("\n"); while (!cells.isEmpty()) { int currentCell = cells.remove(cells.size() - 1); String[] lines = result.substring(currentCell, result.length()).split("\n"); result.delete(currentCell - 1, result.length()); content.add(lines); maxLines = Math.max(maxLines, lines.length); } Collections.reverse(content); for (int line = 0; line < maxLines; line++) { for (int column = 0; column < content.size(); column++) { String[] lines = content.get(column); String currentLine = line < lines.length ? lines[line] : ""; result.append("| "); boolean header = headerFlags.get(column); if (header) { result.append(escape(CODE_HIGHLIGHT)); } result.append(currentLine); if (header) { result.append(escape(CODE_RESET)); } int padding = limit - currentLine.length(); if (padding > 0) result.append(indentString(padding)); result.append(" "); } result.append("|\n"); } for (int sep = 0; sep < (limit + 3) * content.size() + 1; sep++) { result.append("-"); } result.append("\n"); reflownTo = result.length(); break; case TD: case TH: break; default: addSpaceIfNeeded(result); break; } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEntity(EntityTree node, Object p) { String name = node.getName().toString(); int code = -1; if (name.startsWith("#")) { try { int v = StringUtils.toLowerCase(name).startsWith("#x") ? Integer.parseInt(name.substring(2), 16) : Integer.parseInt(name.substring(1), 10); if (Entity.isValid(v)) { code = v; } } catch (NumberFormatException ex) { //ignore } } else { Entity entity = Entity.get(name); if (entity != null) { code = entity.code; } } if (code != (-1)) { result.appendCodePoint(code); } else { result.append(node.toString()); } return super.visitEntity(node, p); } private DocTree lastNode; @Override @DefinedBy(Api.COMPILER_TREE) public Object scan(DocTree node, Object p) { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } try { return super.scan(node, p); } finally { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } lastNode = node; } } private void reflowTillNow() { while (result.length() > 0 && result.charAt(result.length() - 1) == ' ') result.delete(result.length() - 1, result.length()); reflow(result, reflownTo, indent, limit); reflownTo = result.length(); } }; private String escape(String sequence) { return this.escapeSequencesSupported ? sequence : ""; } private static final Map docSections = new LinkedHashMap<>(); static { ResourceBundle bundle = ResourceBundle.getBundle("jdk.internal.shellsupport.doc.resources.javadocformatter"); docSections.put(Sections.TYPE_PARAMS, bundle.getString("CAP_TypeParameters")); docSections.put(Sections.PARAMS, bundle.getString("CAP_Parameters")); docSections.put(Sections.RETURNS, bundle.getString("CAP_Returns")); docSections.put(Sections.THROWS, bundle.getString("CAP_Thrown_Exceptions")); } private static String indentString(int indent) { char[] content = new char[indent]; Arrays.fill(content, ' '); return new String(content); } private static void reflow(StringBuilder text, int from, int indent, int limit) { int lineStart = from; while (lineStart > 0 && text.charAt(lineStart - 1) != '\n') { lineStart--; } int lineChars = from - lineStart; int pointer = from; int lastSpace = -1; while (pointer < text.length()) { if (text.charAt(pointer) == ' ') lastSpace = pointer; if (lineChars >= limit) { if (lastSpace != (-1)) { text.setCharAt(lastSpace, '\n'); text.insert(lastSpace + 1, indentString(indent)); lineChars = indent + pointer - lastSpace - 1; pointer += indent; lastSpace = -1; } } lineChars++; pointer++; } } private static void addNewLineIfNeeded(StringBuilder text) { if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') { text.append("\n"); } } private static void addSpaceIfNeeded(StringBuilder text) { if (text.length() == 0) return ; char last = text.charAt(text.length() - 1); if (last != ' ' && last != '\n') { text.append(" "); } } private static HtmlTag getHtmlTag(Name name) { HtmlTag tag = HtmlTag.get(name); return tag != null ? tag : HtmlTag.HTML; //using HtmlTag.HTML as default no-op value } private static Map countTableColumns(DocCommentTree dct) { Map result = new IdentityHashMap<>(); new DocTreeScanner() { private StartElementTree currentTable; private int currentMaxColumns; private int currentRowColumns; @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { switch (getHtmlTag(node.getName())) { case TABLE: currentTable = node; break; case TR: currentMaxColumns = Math.max(currentMaxColumns, currentRowColumns); currentRowColumns = 0; break; case TD: case TH: currentRowColumns++; break; } return super.visitStartElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitEndElement(EndElementTree node, Void p) { if (HtmlTag.get(node.getName()) == HtmlTag.TABLE) { closeTable(); } return super.visitEndElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitDocComment(DocCommentTree node, Void p) { try { return super.visitDocComment(node, p); } finally { closeTable(); } } private void closeTable() { if (currentTable != null) { result.put(currentTable, Math.max(currentMaxColumns, currentRowColumns)); currentTable = null; } } }.scan(dct, null); return result; } private enum Sections { TYPE_PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && ((ParamTree) t).isTypeParameter(); } }, PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && !((ParamTree) t).isTypeParameter(); } }, RETURNS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.RETURN; } }, THROWS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.THROWS; } }; public abstract boolean matches(DocTree t); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10563 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java/#L70-L712 | 2 | 3996 | 10563 | minor |
| 2459 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14536 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 | 1 | 2459 | 14536 | minor |
| 2616 | {"output": "YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 15048 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 2 | 2616 | 15048 | major |
| 1775 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number (number 3 used multiple times without explanation) 3. Hard-coded values (ex. the array of prefixes and the associated ASCII and unicode values) 4. Use of commented out code 5. Use of synchronized block, potentially leading to threading issues 6. Use of unnecessary casts 7. Confusing naming of variables (ex. "uom" and "power" in getUnit() method) 8. Unused code (ex. the pseudoSystemUnit() method is never called) 9. Redundant code (ex. checks for null in getUnit() method that are already performed in the Units.get() method) 10. Poor formatting and indentation, making the code hard to read and understand. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class Prefixes { /** * The SI “deca” prefix. This is the only SI prefix encoded on two letters instead than one. * It can be represented by the CJK compatibility character “㍲”, but use of those characters * is generally not recommended outside of Chinese, Japanese or Korean texts. */ private static final String DECA = "da"; /** * The SI prefixes in increasing order. The only two-letters prefix – “da” – is encoded using the JCK compatibility * character “㍲”. The Greek letter μ is repeated twice: the U+00B5 character for micro sign (this is the character * that Apache SIS uses in unit symbols) and the U+03BC character for the Greek small letter “mu” (the later is the * character that appears when decomposing JCK compatibility characters with {@link java.text.Normalizer}). * Both characters have same appearance but different values. * * For each prefix at index i, the multiplication factor is given by 10 raised to power {@code POWERS[i]}. */ private static final char[] PREFIXES = {'E','G','M','P','T','Y','Z','a','c','d','f','h','k','m','n','p','y','z','µ','μ','㍲'}; private static final byte[] POWERS = {18, 9, 6, 15, 12, 24, 21,-18, -2, -1,-15, 2, 3, -3, -9,-12,-24,-21, -6, -6, 1}; /** * The SI prefixes from smallest to largest. Power of tens go from -24 to +24 inclusive with a step of 3, * except for the addition of -2, -1, +1, +2 and the omission of 0. * * @see #symbol(double, int) */ private static final char[] ENUM = {'y','z','a','f','p','n','µ','m','c','d','㍲','h','k','M','G','T','P','E','Z','Y'}; /** * The maximal power of 1000 for the prefixes in the {@link #ENUM} array. Note that 1000⁸ = 1E+24. */ static final int MAX_POWER = 8; /** * The converters for SI prefixes, created when first needed. * * @see #converter(char) */ private static final LinearConverter[] CONVERTERS = new LinearConverter[POWERS.length]; /** * Do not allow instantiation of this class. */ private Prefixes() { } /** * Returns the converter for the given SI prefix, or {@code null} if none. * Those converters are created when first needed and cached for reuse. */ static LinearConverter converter(final char prefix) { final int i = Arrays.binarySearch(PREFIXES, prefix); if (i < 0) { return null; } synchronized (CONVERTERS) { LinearConverter c = CONVERTERS[i]; if (c == null) { final int p = POWERS[i]; final double numerator, denominator; if (p >= 0) { numerator = MathFunctions.pow10(p); denominator = 1; } else { numerator = 1; denominator = MathFunctions.pow10(-p); } c = LinearConverter.scale(numerator, denominator); CONVERTERS[i] = c; } return c; } } /** * Returns the SI prefix symbol for the given scale factor, or 0 if none. * * @param scale the scale factor. * @param power the unit power. For example if we are scaling m², then this is 2. * @return the prefix, or 0 if none. */ static char symbol(double scale, final int power) { switch (power) { case 0: return 0; case 1: break; case 2: scale = Math.sqrt(scale); break; case 3: scale = Math.cbrt(scale); break; default: scale = Math.pow(scale, 1.0/power); } final int n = Numerics.toExp10(Math.getExponent(scale)) + 1; if (AbstractConverter.epsilonEquals(MathFunctions.pow10(n), scale)) { int i = Math.abs(n); switch (i) { case 0: return 0; case 1: // Fallthrough case 2: break; default: { if (i > (MAX_POWER*3) || (i % 3) != 0) { return 0; } i = i/3 + 2; break; } } return ENUM[n >= 0 ? (MAX_POWER+1) + i : (MAX_POWER+2) - i]; } return 0; } /** * Returns the concatenation of the given prefix with the given unit symbol. */ static String concat(final char prefix, final String unit) { return (prefix == '㍲') ? DECA + unit : prefix + unit; } /** * Returns the unit for the given symbol, taking the SI prefix in account. The given string is usually a single symbol * like "km", but may be an expression like "m³" or "m/s" if the given symbol is explicitly registered as an item that * {@link Units#get(String)} recognizes. This method does not perform any arithmetic operation on {@code Unit}, * except a check for the exponent. * * @param uom a symbol compliant with the rules documented in {@link AbstractUnit#symbol}. * @return the unit for the given symbol, or {@code null} if no unit is found. */ static Unit getUnit(final String uom) { Unit unit = Units.get(uom); if (unit == null && uom.length() >= 2) { int s = 1; char prefix = uom.charAt(0); if (prefix == 'd' && uom.charAt(1) == 'a') { prefix = '㍲'; // Converse of above 'concat(char, String)' method. s = 2; // Skip "da", which we represent by '㍲'. } unit = Units.get(uom.substring(s)); if (AbstractUnit.isPrefixable(unit)) { LinearConverter c = Prefixes.converter(prefix); if (c != null) { String symbol = unit.getSymbol(); final int power = ConventionalUnit.power(symbol); if (power != 0) { if (power != 1) { c = LinearConverter.pow(c, power, false); } symbol = Prefixes.concat(prefix, symbol); return new ConventionalUnit<>((AbstractUnit) unit, c, symbol.intern(), (byte) 0, (short) 0); } } } unit = null; } return unit; } /** * If the given system unit should be replaced by pseudo-unit for the purpose of formatting, * returns that pseudo-unit. Otherwise returns {@code null}. This method is for handling the * Special case of {@link Units#KILOGRAM}, to be replaced by {@link Units#GRAM} so a prefix * can be computed. The kilogram may appear in an expression like "kg/m", which we want to * replace by "g/m". We do that by dividing the unit by 1000 (the converter for "milli" prefix). */ @SuppressWarnings("unchecked") static > ConventionalUnit pseudoSystemUnit(final SystemUnit unit) { if ((unit.scope & ~UnitRegistry.SI) == 0 && unit.dimension.numeratorIs('M')) { if (unit == Units.KILOGRAM) { return (ConventionalUnit) Units.GRAM; // Optimization for a common case. } else { String symbol = unit.getSymbol(); if (symbol != null && symbol.length() >= 3 && symbol.startsWith("kg") && !AbstractUnit.isSymbolChar(symbol.codePointAt(2))) { symbol = symbol.substring(1); UnitConverter c = converter('m'); return new ConventionalUnit<>(unit, c, symbol, UnitRegistry.PREFIXABLE, (short) 0).unique(symbol); } } } return null; } } |
blob | Long method2 Magic number (number 3 used multiple times without explanation)3 Hard-coded values (ex the array of prefixes and the associated ASCII and unicode values)4 Use of commented out code5 Use of synchronized block, potentially leading to threading issues6 Use of unnecessary casts7 Confusing naming of variables (ex "uom" and "power" in getUnit() method)8 Unused code (ex the pseudoSystemUnit() method is never called)9 Redundant code (ex checks for null in getUnit() method that are already performed in the Unitsget() method) | t | f | f | . Long method2. Magic number (number 3 used multiple times without explanation)3. Hard-coded values (ex. the array of prefixes and the associated ASCII and unicode values)4. Use of commented out code5. Use of synchronized block, potentially leading to threading issues6. Use of unnecessary casts7. Confusing naming of variables (ex. "uom" and "power" in getUnit() method)8. Unused code (ex. the pseudoSystemUnit() method is never called)9. Redundant code (ex. checks for null in getUnit() method that are already performed in the Units.get() method) | blob | 0 | 11942 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-utility/src/main/java/org/apache/sis/measure/Prefixes.java/#L37-L216 | 2 | 1775 | 11942 | minor |
| 1907 | YES I found bad smells the bad smells are: 1. Long class 2. Long method (execute) 3. Data Class (SparkCubingMerge) 4. Inconsistent method names (e.g. getOptions vs execute) 5. Magic numbers/strings (e.g. "segment", "metaUrl") 6. Inconsistent formatting and spacing 7. Feature envy (multiple method calls to instance variables) 8. Dead code (initialized boolean in ReEncodeCuboidFunction) 9. Complex logic and nested functions (ReEncodeCuboidFunction) 10. Code duplication (multiple uses of OPTION_META_URL, OPTION_CUBE_NAME, etc.) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | Long class2 Long method (execute)3 Data Class (SparkCubingMerge)4 Inconsistent method names (eg getOptions vs execute)5 Magic numbers/strings (eg "segment", "metaUrl")6 Inconsistent formatting and spacing7 Feature envy (multiple method calls to instance variables)8 Dead code (initialized boolean in ReEncodeCuboidFunction)9 Complex logic and nested functions (ReEncodeCuboidFunction) | t | f | f | . Long class2. Long method (execute)3. Data Class (SparkCubingMerge)4. Inconsistent method names (e.g. getOptions vs execute)5. Magic numbers/strings (e.g. "segment", "metaUrl")6. Inconsistent formatting and spacing7. Feature envy (multiple method calls to instance variables)8. Dead code (initialized boolean in ReEncodeCuboidFunction)9. Complex logic and nested functions (ReEncodeCuboidFunction) | blob | 0 | 12386 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 2 | 1907 | 12386 | critical |
| 1496 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11125 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1496 | 11125 | minor |
| 2313 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14103 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 1 | 2313 | 14103 | minor |
| 1133 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Duplicate code 5. Magic numbers 6. Inconsistent formatting and naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
data class | Long method2 Feature envy3 Commented out code4 Duplicate code5 Magic numbers6 Inconsistent formatting and naming conventions | t | f | f | . Long method2. Feature envy3. Commented out code4. Duplicate code5. Magic numbers6. Inconsistent formatting and naming conventions | data class | 0 | 10042 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 2 | 1133 | 10042 | minor |
| 1565 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11326 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 1565 | 11326 | minor |
| 759 | YES I found bad smells. The bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 7066 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 759 | 7066 | critical |
| 976 | {"message":"YES I found bad smells","bad smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 8781 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 1 | 976 | 8781 | minor |
| 54 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | long method | t | t | f | long method | data class | 0 | 953 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 2 | 54 | 953 | major |
| 584 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (OptionFormat and OptionOwner classes are accessed multiple times within this class, suggesting a lack of cohesion) 3. Magic numbers/string literals (e.g. "shelvesets", "*", etc) 4. Multiple responsibilities (the CommandShelvesets class handles both querying for shelvesets and printing them, violating the Single Responsibility Principle) 5. Inconsistent naming conventions (e.g. getCanonicalName, versionControlClient, etc) 6. Lack of comments/explanatory text within the code 7. Duplicate code (the same code is repeated multiple times within the run() method) 8. Conditional complexity (the if statements within the run() method increase the complexity of the code) 9. Use of null values (null is used as a parameter for some methods and can potentially cause errors) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | Long method2 Feature envy (OptionFormat and OptionOwner classes are accessed multiple times within this class, suggesting a lack of cohesion)3 Magic numbers/string literals (eg "shelvesets", "*", etc)4 Multiple responsibilities (the CommandShelvesets class handles both querying for shelvesets and printing them, violating the Single Responsibility Principle)5 Inconsistent naming conventions (eg getCanonicalName, versionControlClient, etc)6 Lack of comments/explanatory text within the code7 Duplicate code (the same code is repeated multiple times within the run() method)8 Conditional complexity (the if statements within the run() method increase the complexity of the code)9 Use of null values (null is used as a parameter for some methods and can potentially cause errors) | t | f | f | . Long method2. Feature envy (OptionFormat and OptionOwner classes are accessed multiple times within this class, suggesting a lack of cohesion)3. Magic numbers/string literals (e.g. "shelvesets", "*", etc)4. Multiple responsibilities (the CommandShelvesets class handles both querying for shelvesets and printing them, violating the Single Responsibility Principle)5. Inconsistent naming conventions (e.g. getCanonicalName, versionControlClient, etc)6. Lack of comments/explanatory text within the code7. Duplicate code (the same code is repeated multiple times within the run() method)8. Conditional complexity (the if statements within the run() method increase the complexity of the code)9. Use of null values (null is used as a parameter for some methods and can potentially cause errors) | blob | 0 | 5798 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 2 | 584 | 5798 | major |
| 293 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Serializable implementation 5. Nested classes 6. Inconsistent naming conventions 7. Use of try-with-resources in methods 8. Use of assert statements for checking conditions 9. Excessive use of generics 10. Lack of encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public class SingleThreadAccessCheckingTypeSerializer extends TypeSerializer { private static final long serialVersionUID = 131020282727167064L; private final SingleThreadAccessChecker singleThreadAccessChecker; private final TypeSerializer originalSerializer; public SingleThreadAccessCheckingTypeSerializer(TypeSerializer originalSerializer) { this.singleThreadAccessChecker = new SingleThreadAccessChecker(); this.originalSerializer = originalSerializer; } @Override public boolean isImmutableType() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.isImmutableType(); } } @Override public TypeSerializer duplicate() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializer<>(originalSerializer.duplicate()); } } @Override public T createInstance() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.createInstance(); } } @Override public T copy(T from) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from); } } @Override public T copy(T from, T reuse) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from, reuse); } } @Override public int getLength() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.getLength(); } } @Override public void serialize(T record, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.serialize(record, target); } } @Override public T deserialize(DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(source); } } @Override public T deserialize(T reuse, DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(reuse, source); } } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.copy(source, target); } } @Override public boolean equals(Object obj) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return obj == this || (obj != null && obj.getClass() == getClass() && originalSerializer.equals(obj)); } } @Override public int hashCode() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.hashCode(); } } @Override public TypeSerializerSnapshot snapshotConfiguration() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializerSnapshot<>(this); } } public static class SingleThreadAccessCheckingTypeSerializerSnapshot extends CompositeTypeSerializerSnapshot> { @SuppressWarnings({"unchecked", "unused"}) public SingleThreadAccessCheckingTypeSerializerSnapshot() { super((Class>) (Class) SingleThreadAccessCheckingTypeSerializer.class); } SingleThreadAccessCheckingTypeSerializerSnapshot(SingleThreadAccessCheckingTypeSerializer serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return 1; } @Override protected TypeSerializer[] getNestedSerializers(SingleThreadAccessCheckingTypeSerializer outerSerializer) { return new TypeSerializer[] { outerSerializer.originalSerializer }; } @SuppressWarnings("unchecked") @Override protected SingleThreadAccessCheckingTypeSerializer createOuterSerializerWithNestedSerializers( TypeSerializer[] nestedSerializers) { return new SingleThreadAccessCheckingTypeSerializer<>((TypeSerializer) nestedSerializers[0]); } } private void writeObject(ObjectOutputStream outputStream) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { outputStream.defaultWriteObject(); } } private static class SingleThreadAccessChecker implements Serializable { private static final long serialVersionUID = 131020282727167064L; private transient AtomicReference currentThreadRef = new AtomicReference<>(); SingleThreadAccessCheck startSingleThreadAccessCheck() { assert(currentThreadRef.compareAndSet(null, Thread.currentThread())) : "The checker has concurrent access from " + currentThreadRef.get(); return new SingleThreadAccessCheck(currentThreadRef); } private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { inputStream.defaultReadObject(); currentThreadRef = new AtomicReference<>(); } } private static class SingleThreadAccessCheck implements AutoCloseable { private final AtomicReference currentThreadRef; private SingleThreadAccessCheck(AtomicReference currentThreadRef) { this.currentThreadRef = currentThreadRef; } @Override public void close() { assert(currentThreadRef.compareAndSet(Thread.currentThread(), null)) : "The checker has concurrent access from " + currentThreadRef.get(); } } } |
blob | Long method2 Feature envy 3 Code duplication4 Serializable implementation5 Nested classes 6 Inconsistent naming conventions7 Use of try-with-resources in methods 8 Use of assert statements for checking conditions 9 Excessive use of generics | t | f | f | . Long method2. Feature envy 3. Code duplication4. Serializable implementation5. Nested classes 6. Inconsistent naming conventions7. Use of try-with-resources in methods 8. Use of assert statements for checking conditions 9. Excessive use of generics | blob | 0 | 3080 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/SingleThreadAccessCheckingTypeSerializer.java/#L31-L203 | 2 | 293 | 3080 | minor |
| 154 | { "answer": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String repeat(String s, int c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c; i++) sb.append(s); return sb.toString(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1939 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/shell/src/main/java/org/apache/accumulo/shell/Shell.java/#L1075-L1080 | 1 | 154 | 1939 | minor |
| 1831 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12126 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 2 | 1831 | 12126 | minor |
| 3960 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10368 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 3960 | 10368 | critical |
| 2863 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 1961 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/thrift/ClientService.java/#L33559-L33561 | 1 | 2863 | 1961 | minor | ||
| 3572 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 7855 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 3572 | 7855 | major | ||
| 1802 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Use of static variables and methods within non-static classes 4. Use of inheritance for code reuse instead of composition 5. Use of bare primitive types instead of objects or enums 6. Nested if statements with multiple conditions 7. Non-descriptive variable names 8. Duplicate code in constructor methods 9. Multiple return statements within a single method 10. Magic numbers/strings scattered throughout the code 11. Mixing of responsibilities within a single class 12. Not following proper formatting and indentation 13. Unused imports 14. Poor exception handling 15. Lack of comments or documentation for methods and classes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
blob | Long method2 Feature envy3 Use of static variables and methods within non-static classes4 Use of inheritance for code reuse instead of composition5 Use of bare primitive types instead of objects or enums6 Nested if statements with multiple conditions7 Non-descriptive variable names8 Duplicate code in constructor methods9 Multiple return statements within a single method | t | f | f | . Long method2. Feature envy3. Use of static variables and methods within non-static classes4. Use of inheritance for code reuse instead of composition5. Use of bare primitive types instead of objects or enums6. Nested if statements with multiple conditions7. Non-descriptive variable names8. Duplicate code in constructor methods9. Multiple return statements within a single method | blob | 0 | 12020 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 1802 | 12020 | major |
| 214 | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
data class | f | f | f | data class | 0 | 2325 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 2 | 214 | 2325 | minor | |||
| 723 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6834 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 723 | 6834 | major |
| 2300 | YES I found bad smells the bad smells are: Feature envy, Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Feature envy, Long method | t | f | f | Feature envy, Long method | data class | 0 | 14030 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 2300 | 14030 | major |
| 4054 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10703 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 2 | 4054 | 10703 | major |
| 785 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Primitive obsession (using String for property name instead of creating a specific class) 5. Inappropriate naming (post and pre layout are not clear in their purpose) 6. Using arraylist when a set could be used for layout filters 7. Commented out code (TODOs) 8. Mixing of application logic with layout logic in methods like preLayout() and postLayout() 9. Exposing inner elements (like layout algorithm property) instead of encapsulating them 10. Lack of guard clause in setters 11. Not using specific exceptions in setters 12. Using raw types and not generics 13. Code duplication in getNodes() and getEdges() methods 14. Modifying returned array in getNodes() and getEdges() methods 15. Inconsistent naming convention (sometimes variables are named using camelCase, sometimes they are named using lowercase with underscores) 16. Unused imports | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LayoutContext { /** * An {@link LayoutContext} notifies registered listeners about changes to * the layout algorithm using this property name. */ public static final String LAYOUT_ALGORITHM_PROPERTY = "layoutAlgorithm"; private ObjectProperty layoutAlgorithmProperty = new SimpleObjectProperty<>( this, LAYOUT_ALGORITHM_PROPERTY); private Graph graph; private final List postLayoutPass = new ArrayList<>(); private final List preLayoutPass = new ArrayList<>(); private final List layoutFilters = new ArrayList<>(); /** * Adds the given ILayoutFilter to this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to add to this context. */ public void addLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.add(layoutFilter); } /** * Applies the layout algorithm of this LayoutContext. The clean flag is * passed-in to the layout algorithm to indicate whether the context changed * significantly since the last layout pass. * * @param clear * true to indicate that the algorithm has to fully * re-compute the layout, otherwise false. */ public void applyLayout(boolean clear) { ILayoutAlgorithm layoutAlgorithm = layoutAlgorithmProperty.get(); if (layoutAlgorithm != null) { preLayout(); layoutAlgorithm.applyLayout(this, clear); postLayout(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run after the layout pass. Should not be * called by clients. */ public void postLayout() { for (Runnable r : new ArrayList<>(postLayoutPass)) { r.run(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run before the layout pass. Should not be * called by clients. */ public void preLayout() { for (Runnable r : preLayoutPass) { r.run(); } } /** * Returns the graph that is to be layouted. * * @return The {@link Graph} that is to be layouted. */ public Graph getGraph() { return graph; } /** * Sets the graph that is to be layouted by this context. * * @param graph * The {@link Graph} to layout. */ public void setGraph(Graph graph) { // TODO: we should not allow to pass in null here. Instead we should // guard ourselves against null. if (graph == null) { graph = new Graph(); } this.graph = graph; } /** * Returns all the nodes that should be laid out. Replacing elements in the * returned array does not affect this context. * * @return array of nodes to lay out */ // TODO: remove this (algorithms should use getGraph().getNodes()) public Node[] getNodes() { ObservableList nodes = graph.getNodes(); List layoutRelevantNodes = new ArrayList<>(); for (Node n : nodes) { if (!isLayoutIrrelevant(n)) { layoutRelevantNodes.add(n); } } return layoutRelevantNodes.toArray(new Node[] {}); } /** * Returns all the connections between nodes that should be laid out. * Replacing elements in the returned array does not affect this context. * * @return array of connections between nodes */ public Edge[] getEdges() { ObservableList edges = graph.getEdges(); List layoutRelevantEdges = new ArrayList<>(); for (Edge e : edges) { if (!isLayoutIrrelevant(e)) { layoutRelevantEdges.add(e); } } return layoutRelevantEdges.toArray(new Edge[] {}); } /** * Returns the static layout algorithm used to layout a newly initialized * graph or after heavy changes to it. * * @return The layout algorithm that is used by this {@link LayoutContext}. */ public ILayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithmProperty.get(); } /** * Returns true when the given {@link Edge} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param edge * The {@link Edge} in question. * @return true when the given {@link Edge} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Edge edge) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(edge)) { return true; } } return false; } /** * Returns true when the given {@link Node} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param nodeLayout * The {@link Node} in question. * @return true when the given {@link Node} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Node nodeLayout) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(nodeLayout)) { return true; } } return false; } /** * A property representing the layout algorithm used by this * {@link LayoutContext}. * * @see #getLayoutAlgorithm() * @see #setLayoutAlgorithm(ILayoutAlgorithm) * * @return A property named {@link #LAYOUT_ALGORITHM_PROPERTY}. */ public ObjectProperty layoutAlgorithmProperty() { return layoutAlgorithmProperty; }; /** * Removes the given ILayoutFilter from this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to remove to this context. */ public void removeLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.remove(layoutFilter); } /** * Adds the given {@link Runnable} to the list of runnables which are called * when this {@link LayoutContext} is asked to apply all changes made to its * elements to the display. * * @param runnable * A {@link Runnable} called whenever this context is asked to * apply all changes made to its elements to the display. */ public void schedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!postLayoutPass.contains(runnable)) { postLayoutPass.add(runnable); } } /** * Adds the given {@link Runnable} to the list of {@link Runnable}s which * are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to add to the list of {@link Runnable}s * which are executed before applying a layout. */ public void schedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!preLayoutPass.contains(runnable)) { preLayoutPass.add(runnable); } } /** * Sets the layout algorithm for this context. * * @param algorithm * The new {@link ILayoutAlgorithm} for this * {@link LayoutContext}. */ public void setLayoutAlgorithm(ILayoutAlgorithm algorithm) { layoutAlgorithmProperty.set(algorithm); } /** * Removes the given {@link Runnable} from the list of runnables which are * called when this {@link LayoutContext} is asked to apply all changes made * to its elements to the display. * * @param runnable * The {@link Runnable} that should no longer get called when * flushing changes. */ public void unschedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (postLayoutPass.contains(runnable)) { postLayoutPass.remove(runnable); } } /** * Removes the given {@link Runnable} from the list of {@link Runnable}s * which are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to remove from the list of * {@link Runnable}s which are executed before applying a layout. */ public void unschedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (preLayoutPass.contains(runnable)) { preLayoutPass.remove(runnable); } } } |
blob | Long method 2 Feature envy 3 Duplicate code 4 Primitive obsession (using String for property name instead of creating a specific class) 5 Inappropriate naming (post and pre layout are not clear in their purpose) 6 Using arraylist when a set could be used for layout filters 7 Commented out code (TODOs) 8 Mixing of application logic with layout logic in methods like preLayout() and postLayout() 9 Exposing inner elements (like layout algorithm property) instead of encapsulating them | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Primitive obsession (using String for property name instead of creating a specific class) 5. Inappropriate naming (post and pre layout are not clear in their purpose) 6. Using arraylist when a set could be used for layout filters 7. Commented out code (TODOs) 8. Mixing of application logic with layout logic in methods like preLayout() and postLayout() 9. Exposing inner elements (like layout algorithm property) instead of encapsulating them | blob | 0 | 7497 | https://github.com/eclipse/gef/blob/8f2649b90ab14a1bb010188036d4eedf7586e123/org.eclipse.gef.layout/src/org/eclipse/gef/layout/LayoutContext.java/#L35-L315 | 2 | 785 | 7497 | minor |
| 2175 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate Code 4. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | Long method 2 Feature envy 3 Duplicate Code 4 Inappropriate Intimacy | t | f | f | . Long method 2. Feature envy 3. Duplicate Code 4. Inappropriate Intimacy | data class | 0 | 13394 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 2175 | 13394 | major |
| 1735 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KafkaTestServer { public static final int CACHE_TTL_MS = 1; private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestServer.class); private int kafkaPort = -1; private TestingServer zkServer; private KafkaServerStartable kafkaServer = null; private File sentrySitePath = null; public KafkaTestServer(File sentrySitePath) throws Exception { this.sentrySitePath = sentrySitePath; createZkServer(); this.kafkaPort = TestUtils.getFreePort(); createKafkaServer(); } public void start() throws Exception { kafkaServer.startup(); LOGGER.info("Started Kafka broker."); } public void shutdown() { if (kafkaServer != null) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); LOGGER.info("Stopped Kafka server."); } if (zkServer != null) { try { zkServer.stop(); LOGGER.info("Stopped ZK server."); } catch (IOException e) { LOGGER.error("Failed to shutdown ZK server.", e); } } } private Path getTempDirectory() { Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory("kafka-sentry-"); } catch (IOException e) { LOGGER.error("Failed to create temp dir for Kafka's log dir."); throw new RuntimeException(e); } return tempDirectory; } private void setupKafkaProps(Properties props) throws UnknownHostException { props.put("listeners", "SSL://" + InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort); props.put("log.dir", getTempDirectory().toAbsolutePath().toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controller.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", true); props.put("delete.topic.enable", false); props.put("controlled.shutdown.retry.backoff.ms", "100"); props.put("port", kafkaPort); props.put("offsets.topic.replication.factor", "1"); props.put("authorizer.class.name", "org.apache.sentry.kafka.authorizer.SentryKafkaAuthorizer"); props.put("sentry.kafka.site.url", "file://" + sentrySitePath.getAbsolutePath()); props.put("allow.everyone.if.no.acl.found", "true"); props.put("ssl.keystore.location", KafkaTestServer.class.getResource("/test.keystore.jks").getPath()); props.put("ssl.keystore.password", "test-ks-passwd"); props.put("ssl.key.password", "test-key-passwd"); props.put("ssl.truststore.location", KafkaTestServer.class.getResource("/test.truststore.jks").getPath()); props.put("ssl.truststore.password", "test-ts-passwd"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); props.put(KafkaAuthConf.KAFKA_SUPER_USERS, "User:CN=superuser;User:CN=superuser1; User:CN=Superuser2 "); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_ENABLE_NAME, "true"); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_TTL_MS_NAME, String.valueOf(CACHE_TTL_MS)); } private void createKafkaServer() throws UnknownHostException { Properties props = new Properties(); setupKafkaProps(props); kafkaServer = KafkaServerStartable.fromProps(props); } private void createZkServer() throws Exception { try { zkServer = new TestingServer(); } catch (Exception e) { LOGGER.error("Failed to create testing zookeeper server."); throw new RuntimeException(e); } } public String getBootstrapServers() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11825 | https://github.com/apache/sentry/blob/f859446b65bbc274bc4899464892151eec8217c6/sentry-tests/sentry-tests-kafka/src/main/java/org/apache/sentry/tests/e2e/kafka/KafkaTestServer.java/#L35-L129 | 2 | 1735 | 11825 | minor |
| 2686 | {"message":"YES I found bad smells","the bad smells are":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15279 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 1 | 2686 | 15279 | minor |
| 2163 | YES, I found bad smells. the bad smells are: 1. Large class, 2. Long method, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Large class, 2 Long method, 3 Feature envy | t | f | f | . Large class, 2. Long method, 3. Feature envy | data class | 0 | 13330 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 2163 | 13330 | minor |
| 911 | YES I found bad smells the bad smells are: 1. Long class 2. Too many fields 3. Too many methods 4. Lack of encapsulation (all fields are public) 5. Inconsistent naming convention for methods 6. No comments or documentation for methods 7. Possible feature envy (excessive use of getters) 8. Lack of use of abstraction or inheritance 9. Inconsistent spacing and indentation 10. Redundant method comments (all methods have the same comment) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long class2 Too many fields3 Too many methods4 Lack of encapsulation (all fields are public)5 Inconsistent naming convention for methods6 No comments or documentation for methods7 Possible feature envy (excessive use of getters)8 Lack of use of abstraction or inheritance 9 Inconsistent spacing and indentation | t | f | f | . Long class2. Too many fields3. Too many methods4. Lack of encapsulation (all fields are public)5. Inconsistent naming convention for methods6. No comments or documentation for methods7. Possible feature envy (excessive use of getters)8. Lack of use of abstraction or inheritance 9. Inconsistent spacing and indentation | data class | 0 | 8224 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 911 | 8224 | critical |
| 1980 | YES I found bad smells The bad smells are: 1. Long method 2. Magic numbers 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
blob | Long method2 Magic numbers3 Feature envy | t | f | f | . Long method2. Magic numbers3. Feature envy | blob | 0 | 12638 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 2 | 1980 | 12638 | minor |
| 2255 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13690 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 2 | 2255 | 13690 | minor |
| 4546 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12082 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 2 | 4546 | 12082 | minor |
| 4370 | {"response":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11535 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 4370 | 11535 | major |
| 1039 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TriplesOrQuadsReader extends AbstractRdfReader { @Override protected RecordReader selectRecordReader(Lang lang) throws IOException { if (!RDFLanguages.isQuads(lang) && !RDFLanguages.isTriples(lang)) throw new IOException(lang.getLabel() + " is not a RDF triples/quads format"); if (HadoopRdfIORegistry.hasQuadReader(lang)) { // Supports quads directly return HadoopRdfIORegistry.createQuadReader(lang); } else { // Try to create a triples reader and wrap upwards into quads // This will throw an error if a triple reader is not available return new TriplesToQuadsReader(HadoopRdfIORegistry.createTripleReader(lang)); } } /** * Gets the graph node which represents the graph into which triples will be * indicated to belong to when they are converting into quads. * * Defaults to {@link Quad#defaultGraphNodeGenerated} which represents the * default graph * * * @return Graph node */ protected Node getGraphNode() { return Quad.defaultGraphNodeGenerated; } } |
blob | long method | t | t | f | long method | blob | 0 | 9413 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-elephas/jena-elephas-io/src/main/java/org/apache/jena/hadoop/rdf/io/input/readers/TriplesOrQuadsReader.java/#L40-L70 | 1 | 1039 | 9413 | minor |
| 1380 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Imperative style 5. Poor naming conventions 6. Too many instance variables 7. Violation of Single Responsibility Principle (SRP) 8. Highly coupled code 9. Excessive use of comments 10. Use of hardcoded values instead of constants or variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | Long method2 Feature envy3 Duplicate code4 Imperative style5 Poor naming conventions6 Too many instance variables7 Violation of Single Responsibility Principle (SRP)8 Highly coupled code9 Excessive use of comments | t | f | f | . Long method2. Feature envy3. Duplicate code4. Imperative style5. Poor naming conventions6. Too many instance variables7. Violation of Single Responsibility Principle (SRP)8. Highly coupled code9. Excessive use of comments | blob | 0 | 10819 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 2 | 1380 | 10819 | major |
| 621 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 6238 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 2 | 621 | 6238 | major |
| 1551 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11265 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 1551 | 11265 | minor | ||
| 67 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 1077 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 1 | 67 | 1077 | minor |
| 2608 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LogTransformer extends Transformer { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public Object transformRow(Map row, Context ctx) { String expr = ctx.getEntityAttribute(LOG_TEMPLATE); String level = ctx.replaceTokens(ctx.getEntityAttribute(LOG_LEVEL)); if (expr == null || level == null) return row; if ("info".equals(level)) { if (log.isInfoEnabled()) log.info(ctx.replaceTokens(expr)); } else if ("trace".equals(level)) { if (log.isTraceEnabled()) log.trace(ctx.replaceTokens(expr)); } else if ("warn".equals(level)) { if (log.isWarnEnabled()) log.warn(ctx.replaceTokens(expr)); } else if ("error".equals(level)) { if (log.isErrorEnabled()) log.error(ctx.replaceTokens(expr)); } else if ("debug".equals(level)) { if (log.isDebugEnabled()) log.debug(ctx.replaceTokens(expr)); } return row; } public static final String LOG_TEMPLATE = "logTemplate"; public static final String LOG_LEVEL = "logLevel"; } |
blob | long method | t | t | f | long method | blob | 0 | 15032 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/LogTransformer.java/#L35-L67 | 1 | 2608 | 15032 | minor |
| 1170 | opens = new Open[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10194 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 2 | 1170 | 10194 | minor |
| 1981 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 12639 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 2 | 1981 | 12639 | minor |
| 1979 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12634 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 1 | 1979 | 12634 | critical |
| 1184 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class LdapProtocolUtils { /** A delimiter for the replicaId */ public static final String COOKIE_DELIM = ","; /** the prefix for replicaId value */ public static final String REPLICA_ID_PREFIX = "rid="; public static final int REPLICA_ID_PREFIX_LEN = REPLICA_ID_PREFIX.length(); /** the prefix for Csn value */ public static final String CSN_PREFIX = "csn="; private static final int CSN_PREFIX_LEN = CSN_PREFIX.length(); private static final Logger LOG = LoggerFactory.getLogger( LdapProtocolUtils.class ); private LdapProtocolUtils() { } /** * Extracts request controls from a request to populate into an * OperationContext. * * @param opContext the context to populate with request controls * @param request the request to extract controls from */ public static void setRequestControls( OperationContext opContext, Request request ) { if ( request.getControls() != null ) { opContext .addRequestControls( request.getControls().values().toArray( LdapProtocolConstants.EMPTY_CONTROLS ) ); } } /** * Extracts response controls from a an OperationContext to populate into * a Response object. * * @param opContext the context to extract controls from * @param response the response to populate with response controls */ public static void setResponseControls( OperationContext opContext, Response response ) { response.addAllControls( opContext.getResponseControls() ); } public static byte[] createCookie( int replicaId, String csn ) { // the syncrepl cookie format (compatible with OpenLDAP) // rid=nn,csn=xxxz String replicaIdStr = StringUtils.leftPad( Integer.toString( replicaId ), 3, '0' ); return Strings.getBytesUtf8( REPLICA_ID_PREFIX + replicaIdStr + COOKIE_DELIM + CSN_PREFIX + csn ); } /** * Check the cookie syntax. A cookie must have the following syntax : * { rid={replicaId},csn={CSN} } * * @param cookieString The cookie * @return true if the cookie is valid */ public static boolean isValidCookie( String cookieString ) { if ( ( cookieString == null ) || ( cookieString.trim().length() == 0 ) ) { return false; } int pos = cookieString.indexOf( COOKIE_DELIM ); // position should start from REPLICA_ID_PREFIX_LEN or higher cause a cookie can be // like "rid=0,csn={csn}" or "rid=11,csn={csn}" if ( pos <= REPLICA_ID_PREFIX_LEN ) { return false; } String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, pos ); try { Integer.parseInt( replicaId ); } catch ( NumberFormatException e ) { LOG.debug( "Failed to parse the replica id {}", replicaId ); return false; } if ( pos == cookieString.length() ) { return false; } String csnString = cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); return Csn.isValid( csnString ); } /** * returns the CSN present in cookie * * @param cookieString the cookie * @return The CSN */ public static String getCsn( String cookieString ) { int pos = cookieString.indexOf( COOKIE_DELIM ); return cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); } /** * returns the replica id present in cookie * * @param cookieString the cookie * @return The replica Id */ public static int getReplicaId( String cookieString ) { String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, cookieString.indexOf( COOKIE_DELIM ) ); return Integer.parseInt( replicaId ); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 10239 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolUtils.java/#L38-L171 | 1 | 1184 | 10239 | minor |
| 2872 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 2003 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 2 | 2872 | 2003 | minor | ||
| 1904 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12369 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 | 1 | 1904 | 12369 | major |
| 158 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1979 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 158 | 1979 | minor |
| 1449 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10991 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 1449 | 10991 | minor |
| 690 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GrpcXceiverService extends XceiverClientProtocolServiceGrpc.XceiverClientProtocolServiceImplBase { public static final Logger LOG = LoggerFactory.getLogger(GrpcXceiverService.class); private final ContainerDispatcher dispatcher; private final boolean isGrpcTokenEnabled; private final TokenVerifier tokenVerifier; public GrpcXceiverService(ContainerDispatcher dispatcher) { this(dispatcher, false, null); } public GrpcXceiverService(ContainerDispatcher dispatcher, boolean grpcTokenEnabled, TokenVerifier tokenVerifier) { this.dispatcher = dispatcher; this.isGrpcTokenEnabled = grpcTokenEnabled; this.tokenVerifier = tokenVerifier; } @Override public StreamObserver send( StreamObserver responseObserver) { return new StreamObserver() { private final AtomicBoolean isClosed = new AtomicBoolean(false); @Override public void onNext(ContainerCommandRequestProto request) { try { if(isGrpcTokenEnabled) { // ServerInterceptors intercepts incoming request and creates ugi. tokenVerifier.verify(UserGroupInformation.getCurrentUser() .getShortUserName(), request.getEncodedToken()); } ContainerCommandResponseProto resp = dispatcher.dispatch(request, null); responseObserver.onNext(resp); } catch (Throwable e) { LOG.error("{} got exception when processing" + " ContainerCommandRequestProto {}: {}", request, e); responseObserver.onError(e); } } @Override public void onError(Throwable t) { // for now we just log a msg LOG.error("{}: ContainerCommand send on error. Exception: {}", t); } @Override public void onCompleted() { if (isClosed.compareAndSet(false, true)) { LOG.debug("{}: ContainerCommand send completed"); responseObserver.onCompleted(); } } }; } } |
blob | long method | t | t | f | long method | blob | 0 | 6650 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java/#L38-L97 | 1 | 690 | 6650 | minor |
| 153 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1932 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 1 | 153 | 1932 | minor |
| 1625 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11499 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 1625 | 11499 | major |
| 183 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2095 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 1 | 183 | 2095 | minor |
| 3238 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 5441 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 1 | 3238 | 5441 | minor |
| 62 | { "message": "YES I found bad smells", "detected bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue.Builder public abstract static class Builder { public abstract Builder setCompileTimeConstant(boolean compileTimeConstant); public abstract Builder setStatic(boolean isStatic); public abstract Builder setFinal(boolean isFinal); public abstract Builder setVariableCapture(boolean isVariableCapture); public abstract Builder setEnclosingInstanceCapture(boolean isEnclosingInstanceCapture); public abstract Builder setEnclosingTypeDescriptor( DeclaredTypeDescriptor enclosingTypeDescriptor); public abstract Builder setName(String name); public abstract Builder setEnumConstant(boolean isEnumConstant); public abstract Builder setSynthetic(boolean isSynthetic); public abstract Builder setTypeDescriptor(TypeDescriptor typeDescriptor); public abstract Builder setVisibility(Visibility visibility); public abstract Builder setJsInfo(JsInfo jsInfo); public abstract Builder setUnusableByJsSuppressed(boolean isUnusableByJsSuppressed); public abstract Builder setDeprecated(boolean isDeprecated); public abstract Builder setOrigin(FieldOrigin fieldOrigin); public Builder setDeclarationFieldDescriptor(FieldDescriptor declarationFieldDescriptor) { return setDeclarationFieldDescriptorOrNullIfSelf(declarationFieldDescriptor); } // Accessors to support validation, default construction and custom setters. abstract Builder setDeclarationFieldDescriptorOrNullIfSelf( FieldDescriptor declarationFieldDescriptor); abstract Optional getName(); abstract FieldDescriptor autoBuild(); public FieldDescriptor build() { checkState(getName().isPresent()); FieldDescriptor fieldDescriptor = autoBuild(); checkState( !fieldDescriptor.isVariableCapture() || !fieldDescriptor.isEnclosingInstanceCapture()); return interner.intern(fieldDescriptor); } public static Builder from(FieldDescriptor fieldDescriptor) { return fieldDescriptor.toBuilder(); } private static final ThreadLocalInterner interner = new ThreadLocalInterner<>(); } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1048 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/ast/FieldDescriptor.java/#L194-L255 | 2 | 62 | 1048 | major |
| 118 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @NonNull public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 1509 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java/#L426-L430 | 1 | 118 | 1509 | critical |
| 273 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2935 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 273 | 2935 | major |
| 3387 | so far NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 6559 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L241837-L241908 | 2 | 3387 | 6559 | minor | ||
| 2379 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Duplicate code 5. Poor exception handling 6. Inconsistent formatting and naming conventions 7. Low cohesion 8. Lack of comments/documentation 9. Magic numbers/strings used without explanation 10. Complex conditional logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Duplicate code5 Poor exception handling 6 Inconsistent formatting and naming conventions7 Low cohesion8 Lack of comments/documentation 9 Magic numbers/strings used without explanation | t | f | f | . Long method2. Feature envy3. Primitive obsession4. Duplicate code5. Poor exception handling 6. Inconsistent formatting and naming conventions7. Low cohesion8. Lack of comments/documentation 9. Magic numbers/strings used without explanation | data class | 0 | 14336 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 2379 | 14336 | minor |
| 2462 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 14549 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 2 | 2462 | 14549 | minor |
| 1133 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
data class | feature envy | t | t | f | feature envy | data class | 0 | 10042 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 1 | 1133 | 10042 | minor |
| 1856 | { "output": "YES I found bad smells\nthe bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 12215 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 1856 | 12215 | minor |
| 3053 | {"response": "YES I found bad smells the bad smells are:1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | feature envy | 0 | 3501 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 3053 | 3501 | minor |
| 359 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3692 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 1 | 359 | 3692 | minor |
| 2334 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14160 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 2334 | 14160 | minor |
| 1049 | YES I found bad smells the bad smells are: 1. Method with a long code block 2. Repeated calls to getValueAccessorById() 3. Repeated calls to getValueVectorId() 4. AllocationHelper being used twice without any logic or condition 5. Non-descriptive variable names (e.g. fragmentIdVector) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | Method with a long code block2 Repeated calls to getValueAccessorById()3 Repeated calls to getValueVectorId()4 AllocationHelper being used twice without any logic or condition5 Non-descriptive variable names (eg fragmentIdVector) | t | f | f | . Method with a long code block2. Repeated calls to getValueAccessorById()3. Repeated calls to getValueVectorId()4. AllocationHelper being used twice without any logic or condition5. Non-descriptive variable names (e.g. fragmentIdVector) | feature envy | 0 | 9463 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1049 | 9463 | minor |
| 1594 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11407 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 1594 | 11407 | critical |
| 3914 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 10245 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 | 2 | 3914 | 10245 | major |
| 1823 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12103 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 2 | 1823 | 12103 | minor |
| 1855 | {"output": "YES I found bad smells the bad smells are: 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
blob | 2. feature envy | t | t | f | 2. feature envy | blob | 0 | 12207 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 1 | 1855 | 12207 | minor |
| 2348 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14198 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 2 | 2348 | 14198 | major |
| 161 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 1994 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 1 | 161 | 1994 | minor |
| 1598 | {"response": "YES I found bad smells the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | t | f | f | data class | 0 | 11417 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 1598 | 11417 | minor | ||
| 3573 | NO, I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 7856 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 3573 | 7856 | minor | ||
| 742 | YES, I found bad smells the Bad smells are: 1. Long method 2. Multiple class responsibilities 3. Poor naming conventions 4. Lack of separation of concerns 5. Violation of encapsulation 6. Tight coupling 7. Unnecessary complexity and duplication of code 8. Lack of error handling 9. Poor use of inheritance (extending Canvas instead of creating a separate class) 10. Use of magic numbers (e.g. 2, 16, 5) instead of named constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
blob | Long method2 Multiple class responsibilities3 Poor naming conventions4 Lack of separation of concerns5 Violation of encapsulation6 Tight coupling7 Unnecessary complexity and duplication of code8 Lack of error handling9 Poor use of inheritance (extending Canvas instead of creating a separate class) | t | f | f | . Long method2. Multiple class responsibilities3. Poor naming conventions4. Lack of separation of concerns5. Violation of encapsulation6. Tight coupling7. Unnecessary complexity and duplication of code8. Lack of error handling9. Poor use of inheritance (extending Canvas instead of creating a separate class) | blob | 0 | 6976 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 742 | 6976 | major |
| 2190 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 13458 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 2 | 2190 | 13458 | minor |
| 1825 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 12107 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 1 | 1825 | 12107 | minor | ||
| 1671 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
blob | long method | t | t | f | long method | blob | 0 | 11636 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1671 | 11636 | minor |
| 2663 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 15198 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2663 | 15198 | minor |
| 1546 | {"result": "YES I found bad smells", "bad smells are": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Service ("knownRepositoryContentConsumer#create-archiva-metadata") @Scope ("prototype") public class ArchivaMetadataCreationConsumer extends AbstractMonitoredConsumer implements KnownRepositoryContentConsumer, RegistryListener { private String id = "create-archiva-metadata"; private String description = "Create basic metadata for Archiva to be able to reference the artifact"; @Inject private ArchivaConfiguration configuration; @Inject private FileTypes filetypes; private Date whenGathered; private List includes = new ArrayList<>( 0 ); /** * FIXME: this could be multiple implementations and needs to be configured. */ @Inject private RepositorySessionFactory repositorySessionFactory; /** * FIXME: this needs to be configurable based on storage type - and could also be instantiated per repo. Change to a * factory. */ @Inject @Named (value = "repositoryStorage#maven2") private RepositoryStorage repositoryStorage; private static final Logger log = LoggerFactory.getLogger( ArchivaMetadataCreationConsumer.class ); private String repoId; @Override public String getId() { return this.id; } @Override public String getDescription() { return this.description; } @Override public List getExcludes() { return getDefaultArtifactExclusions(); } @Override public List getIncludes() { return this.includes; } @Override public void beginScan( ManagedRepository repo, Date whenGathered ) throws ConsumerException { repoId = repo.getId(); this.whenGathered = whenGathered; } @Override public void beginScan( ManagedRepository repository, Date whenGathered, boolean executeOnEntireRepo ) throws ConsumerException { beginScan( repository, whenGathered ); } @Override public void processFile( String path ) throws ConsumerException { RepositorySession repositorySession = repositorySessionFactory.createSession(); try { // note that we do minimal processing including checksums and POM information for performance of // the initial scan. Any request for this information will be intercepted and populated on-demand // or picked up by subsequent scans ArtifactMetadata artifact = repositoryStorage.readArtifactMetadataFromPath( repoId, path ); ProjectMetadata project = new ProjectMetadata(); project.setNamespace( artifact.getNamespace() ); project.setId( artifact.getProject() ); String projectVersion = VersionUtil.getBaseVersion( artifact.getVersion() ); MetadataRepository metadataRepository = repositorySession.getRepository(); boolean createVersionMetadata = false; // FIXME: maybe not too efficient since it may have already been read and stored for this artifact ProjectVersionMetadata versionMetadata = null; try { ReadMetadataRequest readMetadataRequest = new ReadMetadataRequest().repositoryId( repoId ).namespace( artifact.getNamespace() ).projectId( artifact.getProject() ).projectVersion( projectVersion ); versionMetadata = repositoryStorage.readProjectVersionMetadata( readMetadataRequest ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataNotFoundException e ) { log.warn( "Missing or invalid POM for artifact:{} (repository:{}); creating empty metadata", path, repoId ); versionMetadata = new ProjectVersionMetadata(); versionMetadata.setId( projectVersion ); versionMetadata.setIncomplete( true ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataInvalidException e ) { log.warn( "Error occurred resolving POM for artifact:{} (repository:{}); message: {}", new Object[]{ path, repoId, e.getMessage() } ); } // read the metadata and update it if it is newer or doesn't exist artifact.setWhenGathered( whenGathered ); metadataRepository.updateArtifact( repoId, project.getNamespace(), project.getId(), projectVersion, artifact ); if ( createVersionMetadata ) { metadataRepository.updateProjectVersion( repoId, project.getNamespace(), project.getId(), versionMetadata ); } metadataRepository.updateProject( repoId, project ); repositorySession.save(); } catch ( MetadataRepositoryException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}" , path, repoId, e.getMessage(), e ); repositorySession.revert(); } catch ( RepositoryStorageRuntimeException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}", path, repoId, e.getMessage(), e ); repositorySession.revert(); } finally { repositorySession.close(); } } @Override public void processFile( String path, boolean executeOnEntireRepo ) throws ConsumerException { processFile( path ); } @Override public void completeScan() { /* do nothing */ } @Override public void completeScan( boolean executeOnEntireRepo ) { completeScan(); } @Override public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { if ( ConfigurationNames.isRepositoryScanning( propertyName ) ) { initIncludes(); } } @Override public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { /* do nothing */ } private void initIncludes() { includes = new ArrayList( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) ); } @PostConstruct public void initialize() { configuration.addChangeListener( this ); initIncludes(); } } |
blob | 2 Data Class | t | f | f | 2. Data Class | blob | 0 | 11252 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-consumers/archiva-metadata-consumer/src/main/java/org/apache/archiva/consumers/metadata/ArchivaMetadataCreationConsumer.java/#L59-L264 | 1 | 1546 | 11252 | minor |
| 1231 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10364 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 1231 | 10364 | critical |
| 916 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransactionIdConversion { static KahaTransactionInfo convertToLocal(TransactionId tx) { KahaTransactionInfo rc = new KahaTransactionInfo(); LocalTransactionId t = (LocalTransactionId) tx; KahaLocalTransactionId kahaTxId = new KahaLocalTransactionId(); kahaTxId.setConnectionId(t.getConnectionId().getValue()); kahaTxId.setTransactionId(t.getValue()); rc.setLocalTransactionId(kahaTxId); return rc; } static KahaTransactionInfo convert(TransactionId txid) { if (txid == null) { return null; } KahaTransactionInfo rc; if (txid.isLocalTransaction()) { rc = convertToLocal(txid); } else { rc = new KahaTransactionInfo(); XATransactionId t = (XATransactionId) txid; KahaXATransactionId kahaTxId = new KahaXATransactionId(); kahaTxId.setBranchQualifier(new Buffer(t.getBranchQualifier())); kahaTxId.setGlobalTransactionId(new Buffer(t.getGlobalTransactionId())); kahaTxId.setFormatId(t.getFormatId()); rc.setXaTransactionId(kahaTxId); } return rc; } static TransactionId convert(KahaTransactionInfo transactionInfo) { if (transactionInfo.hasLocalTransactionId()) { KahaLocalTransactionId tx = transactionInfo.getLocalTransactionId(); LocalTransactionId rc = new LocalTransactionId(); rc.setConnectionId(new ConnectionId(tx.getConnectionId())); rc.setValue(tx.getTransactionId()); return rc; } else { KahaXATransactionId tx = transactionInfo.getXaTransactionId(); XATransactionId rc = new XATransactionId(); rc.setBranchQualifier(tx.getBranchQualifier().toByteArray()); rc.setGlobalTransactionId(tx.getGlobalTransactionId().toByteArray()); rc.setFormatId(tx.getFormatId()); return rc; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8247 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/TransactionIdConversion.java/#L29-L77 | 2 | 916 | 8247 | minor |
| 244 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2649 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 2 | 244 | 2649 | major |
| 2083 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | Feature envy | t | f | f | . Feature envy | blob | 0 | 13077 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 2 | 2083 | 13077 | minor |
| 948 | YES, I found code smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8508 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 948 | 8508 | minor |
| 368 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3790 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 368 | 3790 | major |
| 1924 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12432 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 1 | 1924 | 12432 | major |
| 412 | { "error": "Input does not match the expected format. Please provide a list of code smells to check for and the Java code to analyze." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | f | f | f | data class | 0 | 4215 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 412 | 4215 | critical | ||
| 1404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10872 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 1404 | 10872 | major |
| 1832 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Lack of comments/documentation 5. Inappropriate naming conventions (e.g. variables named with abbreviations) 6. Nested if-else statements 7. Redundant code 8. Lack of error handling 9. Code duplication 10. Lack of encapsulation/modularity 11. Non-descriptive naming conventions 12. Not following best coding practices (e.g. using Thread.sleep() instead of ScheduledExecutorService) 13. Using a semaphore as a means of loop control 14. Lack of meaningful separation of concerns (e.g. mixing job execution logic with metrics/logging) 15. Inconsistent use of logger (e.g. sometimes using logger.debug() and other times using logger.error() for the same information) 16. Unnecessary use of try-catch blocks | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
data class | Long method2 Feature envy3 Magic numbers4 Lack of comments/documentation5 Inappropriate naming conventions (eg variables named with abbreviations)6 Nested if-else statements7 Redundant code8 Lack of error handling9 Code duplication | t | f | f | . Long method2. Feature envy3. Magic numbers4. Lack of comments/documentation5. Inappropriate naming conventions (e.g. variables named with abbreviations)6. Nested if-else statements7. Redundant code8. Lack of error handling9. Code duplication | data class | 0 | 12128 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 2 | 1832 | 12128 | minor |
| 1392 | {"response": "YES I found bad smells", "detected_bad_smells": ["2. Long Method", "3. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | 2. long method, 3. data class | t | t | f | 2. long method, 3. data class | blob | 0 | 10844 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 1 | 1392 | 10844 | minor |
| 879 | YES I found bad smells The bad smells are: 1. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method | t | f | f | . Long method. | feature envy | 0 | 8015 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 879 | 8015 | minor |
| 11 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ZooInspectorPanel extends JPanel implements NodeViewersChangeListener { private final IconResource iconResource; private final Toolbar toolbar; private final ZooInspectorNodeViewersPanel nodeViewersPanel; private final ZooInspectorTreeViewer treeViewer; private final ZooInspectorManager zooInspectorManager; private final List listeners = new ArrayList(); { listeners.add(this); } /** * @param zooInspectorManager * - the {@link ZooInspectorManager} for the application */ public ZooInspectorPanel(final ZooInspectorManager zooInspectorManager, final IconResource iconResource) { this.zooInspectorManager = zooInspectorManager; this.iconResource = iconResource; toolbar = new Toolbar(iconResource); final List nodeViewers = new ArrayList(); try { List defaultNodeViewersClassNames = this.zooInspectorManager .getDefaultNodeViewerConfiguration(); for (String className : defaultNodeViewersClassNames) { nodeViewers.add((ZooInspectorNodeViewer) Class.forName( className).newInstance()); } } catch (Exception ex) { LoggerFactory.getLogger().error( "Error loading default node viewers.", ex); JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Error loading default node viewers: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } nodeViewersPanel = new ZooInspectorNodeViewersPanel( zooInspectorManager, nodeViewers); treeViewer = new ZooInspectorTreeViewer(zooInspectorManager, nodeViewersPanel, iconResource); this.setLayout(new BorderLayout()); toolbar.addActionListener(Toolbar.Button.connect, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorConnectionPropertiesDialog zicpd = new ZooInspectorConnectionPropertiesDialog( zooInspectorManager.getLastConnectionProps(), zooInspectorManager.getConnectionPropertiesTemplate(), ZooInspectorPanel.this); zicpd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.disconnect, new ActionListener() { public void actionPerformed(ActionEvent e) { disconnect(); } }); toolbar.addActionListener(Toolbar.Button.refresh, new ActionListener() { public void actionPerformed(ActionEvent e) { treeViewer.refreshView(); } }); toolbar.addActionListener(Toolbar.Button.addNode, new AddNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.deleteNode, new DeleteNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.nodeViewers, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorNodeViewersDialog nvd = new ZooInspectorNodeViewersDialog( JOptionPane.getRootFrame(), nodeViewers, listeners, zooInspectorManager, iconResource); nvd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.about, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorAboutDialog zicpd = new ZooInspectorAboutDialog( JOptionPane.getRootFrame(), iconResource); zicpd.setVisible(true); } }); JScrollPane treeScroller = new JScrollPane(treeViewer); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroller, nodeViewersPanel); splitPane.setResizeWeight(0.25); this.add(splitPane, BorderLayout.CENTER); this.add(toolbar.getJToolBar(), BorderLayout.NORTH); } /** * @param connectionProps * the {@link Properties} for connecting to the zookeeper * instance */ public void connect(final Properties connectionProps) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { zooInspectorManager.setLastConnectionProps(connectionProps); return zooInspectorManager.connect(connectionProps); } @Override protected void done() { try { if (get()) { treeViewer.refreshView(); toolbar.toggleButtons(true); } else { JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Unable to connect to zookeeper", "Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } } }; worker.execute(); } /** * */ public void disconnect() { disconnect(false); } /** * @param wait * - set this to true if the method should only return once the * application has successfully disconnected */ public void disconnect(boolean wait) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { return ZooInspectorPanel.this.zooInspectorManager.disconnect(); } @Override protected void done() { try { if (get()) { treeViewer.clearView(); toolbar.toggleButtons(false); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } }; worker.execute(); if (wait) { while (!worker.isDone()) { try { Thread.sleep(100); } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } } } /* * (non-Javadoc) * * @seeorg.apache.zookeeper.inspector.gui.NodeViewersChangeListener# * nodeViewersChanged(java.util.List) */ public void nodeViewersChanged(List newViewers) { this.nodeViewersPanel.setNodeViewers(newViewers); } /** * @param connectionProps * @throws IOException */ public void setdefaultConnectionProps(Properties connectionProps) throws IOException { this.zooInspectorManager.saveDefaultConnectionFile(connectionProps); } } |
blob | Not specified | f | f | f | false | 0 | 614 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/org/apache/zookeeper/inspector/gui/ZooInspectorPanel.java/#L46-L258 | 2 | 11 | 614 | minor | |
| 2172 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13384 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 2172 | 13384 | minor |
| 612 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void serialize(AGeometry instance, DataOutput out) throws HyracksDataException { try { OGCGeometry geometry = instance.getGeometry(); byte[] buffer = geometry.asBinary().array(); // For efficiency, we store the size of the geometry in bytes in the first 32 bits // This allows AsterixDB to skip over this attribute if needed. out.writeInt(buffer.length); out.write(buffer); } catch (IOException e) { throw HyracksDataException.create(e); } } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 6154 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/serde/AGeometrySerializerDeserializer.java/#L63-L75 | 1 | 612 | 6154 | major |
| 1648 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | Long method | t | f | f | .Long method | feature envy | 0 | 11565 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 2 | 1648 | 11565 | major |
| 262 | {"message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2850 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 262 | 2850 | critical |
| 3248 | {"message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 5487 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 2 | 3248 | 5487 | major |
| 1017 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9315 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 2 | 1017 | 9315 | minor |
| 416 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; private final AbstractPathConfiguration classpathConfiguration; private final ClassLoaderConfiguration classLoaderConfiguration; private final boolean isForkRequested; private final boolean isInForkedVm; public StartupConfiguration( @Nonnull String providerClassName, @Nonnull AbstractPathConfiguration classpathConfiguration, @Nonnull ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } public boolean isProviderMainClass() { return providerClassName.endsWith( "#main" ); } public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) { return new StartupConfiguration( providerClassName, classpathConfiguration, classLoaderConfiguration, true, true ); } public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } @Deprecated public boolean useSystemClassLoader() { // todo; I am not totally convinced this logic is as simple as it could be return classLoaderConfiguration.isUseSystemClassLoader() && ( isInForkedVm || isForkRequested ); } public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } public String getProviderClassName() { return providerClassName; } public String getActualClassName() { return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; } /** * Strip any of a supplied String from the end of a String. * * If the strip String is {@code null}, whitespace is * stripped. * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ private static String stripEnd( String str, String strip ) { if ( str == null ) { return null; } int end = str.length(); if ( strip == null ) { while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) { end--; } } else { while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) { end--; } } return str.substring( 0, end ); } public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } public boolean isShadefire() { return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); } public void writeSurefireTestClasspathProperty() { getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); } } |
blob | f | f | f | blob | 0 | 4224 | https://github.com/apache/maven-surefire/blob/e57f76c7e858dbbaac6be4cbcd16e215de10b064/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java/#L29-L140 | 2 | 416 | 4224 | minor | ||
| 5025 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 13928 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 2 | 5025 | 13928 | major |
| 1598 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11417 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 1598 | 11417 | minor |
| 362 | YES, I found bad smells The bad smells are: 1.Duplicated Code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Listener(clustered = false, sync = false) public class InfinispanAsyncLocalEventListener extends InfinispanSyncLocalEventListener { public InfinispanAsyncLocalEventListener(InfinispanConsumer consumer, Set eventTypes) { super(consumer, eventTypes); } } |
data class | Duplicated Code | t | f | f | .Duplicated Code | data class | 0 | 3707 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanAsyncLocalEventListener.java/#L24-L29 | 2 | 362 | 3707 | major |
| 4527 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12002 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L241837-L241908 | 1 | 4527 | 12002 | minor | ||
| 2263 | {"response":"YES I found bad smells","the bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13723 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 2 | 2263 | 13723 | major |
| 1764 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11900 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 2 | 1764 | 11900 | minor |
| 2318 | YES I found bad smells! The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14124 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 2318 | 14124 | minor |
| 1727 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | f | f | f | long method | 0 | 11810 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 1727 | 11810 | minor | ||
| 47 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 840 | https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 | 2 | 47 | 840 | minor |
| 1532 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11209 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 1532 | 11209 | major |
| 446 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | blob | t | t | f | blob | data class | 0 | 4357 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 1 | 446 | 4357 | major |
| 4054 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
blob | long method | t | t | f | long method | blob | 0 | 10703 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 1 | 4054 | 10703 | major |
| 1988 | NO, I did not find any bad smells. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
blob | f | f | f | blob | 0 | 12677 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 2 | 1988 | 12677 | minor | ||
| 2675 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data clump 4. Large class 5. Primitive obsession 6. Lazy element 7. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | Long method2 Feature envy3 Data clump4 Large class5 Primitive obsession6 Lazy element7 Inappropriate intimacy | t | f | f | . Long method2. Feature envy3. Data clump4. Large class5. Primitive obsession6. Lazy element7. Inappropriate intimacy | data class | 0 | 15229 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 2675 | 15229 | major |
| 2266 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named) 3. Primitive obsession (using primitive data types instead of creating custom objects) 4. Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName) 5. Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values) 6. Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values) 7. Unnecessary use of final keyword (attributes are declared as final but never reassigned) 8. Inconsistent formatting (some attributes have spaces after the '=' while others do not) 9. Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) 10. Inefficient use of StringBuilder in the overridden method (using a StringBuilder to concatenate a single String value) 11. Unnecessary indentation (the constructor and the overridden method are indented differently) 12. Inconsistent naming conventions (some attributes use camelCase while others use snake_case) 13. Use of public attributes instead of private with getters and setters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | Long method 2 Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named)3 Primitive obsession (using primitive data types instead of creating custom objects)4 Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName)5 Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values)6 Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values)7 Unnecessary use of final keyword (attributes are declared as final but never reassigned)8 Inconsistent formatting (some attributes have spaces after the '=' while others do not)9 Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) | t | f | f | . Long method 2. Feature envy (MetaColumn class has too much knowledge about other classes, such as DataType and Named)3. Primitive obsession (using primitive data types instead of creating custom objects)4. Data clumps (multiple attributes related to the same concept - tableCat, tableSchem, tableName)5. Duplicated code (the constructor and the overridden method both use the same logic for assigning attribute values)6. Use of null values (bufferLength = null, remarks = null, columnDef = null, sqlDataType = null, sqlDatetimeSub = null are all assigned null values)7. Unnecessary use of final keyword (attributes are declared as final but never reassigned)8. Inconsistent formatting (some attributes have spaces after the '=' while others do not)9. Unnecessary use of @NotNull annotation (isAutoincrement and isGeneratedcolumn are assigned empty strings and do not need to be checked for null values) | data class | 0 | 13732 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 2266 | 13732 | critical |
| 14 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | Not specified | f | f | f | false | 0 | 623 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 14 | 623 | critical | |
| 5274 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14746 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5274 | 14746 | minor | ||
| 910 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
blob | long method | t | t | f | long method | blob | 0 | 8215 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 1 | 910 | 8215 | major |
| 2420 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14428 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 2420 | 14428 | minor |
| 147 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AttributeUtils { public static Attribute[] readAttributes(DataInputStream dataInputstream, ConstantPool cpool) { try { int length = dataInputstream.readUnsignedShort(); if (length == 0) { return Attribute.NoAttributes; } Attribute[] attrs = new Attribute[length]; for (int i = 0; i < length; i++) { attrs[i] = Attribute.readAttribute(dataInputstream, cpool); } return attrs; } catch (IOException e) { throw new ClassFormatException("IOException whilst reading set of attributes: " + e.toString()); } } /** Write (serialize) a set of attributes into a specified output stream */ public static void writeAttributes(Attribute[] attributes, DataOutputStream file) throws IOException { if (attributes == null) { file.writeShort(0); } else { file.writeShort(attributes.length); for (int i = 0; i < attributes.length; i++) { attributes[i].dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SIGNATURE) { return (Signature) attributes[i]; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_CODE) { return (Code) attributes[i]; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { return (ExceptionTable) attributes[i]; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { return (ConstantValue) attributes[i]; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { for (int i = 0; i < attributes.length; i++) { attributes[i].accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { return true; } } return false; } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { return (SourceFile) attributes[i]; } } return null; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1836 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java/#L9-L99 | 2 | 147 | 1836 | major |
| 5778 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | f | f | f | feature envy | 0 | 15214 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5778 | 15214 | minor | ||
| 60 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Long parameter list", "Switch statements", "Data class", "Data clumps" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | long method, long parameter list, switch statements, data class, data clumps | t | t | f | long method, long parameter list, switch statements, data class, data clumps | blob | 0 | 1007 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 2 | 60 | 1007 | major |
| 5382 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 15137 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 2 | 5382 | 15137 | minor |
| 2701 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 15329 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 2 | 2701 | 15329 | minor |
| 920 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8275 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 920 | 8275 | major |
| 2472 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuckAddDependencyIntention extends BaseIntentionAction { private static Logger LOGGER = Logger.getInstance(BuckAddDependencyIntention.class); /** * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the * given reference element to those of the given psiClass. * * Note that this intention can fail to be created if either side of the edge cannot be * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking * this intention may fail to create edges in either the Buck target graph or the IntelliJ module * graph (or both). */ @Nullable public static BuckAddDependencyIntention create( PsiJavaCodeReferenceElement referenceElement, PsiClass psiClass) { VirtualFile editSourceFile = referenceElement.getContainingFile().getVirtualFile(); if (editSourceFile == null) { return null; } Project project = referenceElement.getProject(); BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); VirtualFile editBuildFile = buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null); if (editBuildFile == null) { return null; } VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile(); if (importSourceFile == null) { return null; } VirtualFile importBuildFile = buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null); if (importBuildFile == null) { return null; } if (importBuildFile.equals(editBuildFile)) { return null; } ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); Module editModule = projectFileIndex.getModuleForFile(editSourceFile); if (editModule == null) { return null; } Module importModule = projectFileIndex.getModuleForFile(importSourceFile); if (importModule == null) { return null; } BuckTarget editSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(editSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (editSourceTarget == null) { return null; } BuckTarget importSourceTarget = buckTargetLocator .findTargetPatternForVirtualFile(importSourceFile) .flatMap(BuckTargetPattern::asBuckTarget) .orElse(null); if (importSourceTarget == null) { return null; } return new BuckAddDependencyIntention( project, referenceElement, editBuildFile, editSourceFile, editSourceTarget, editModule, psiClass, importBuildFile, importSourceFile, importSourceTarget, importModule); } private Project project; // Fields pertaining to the element in the file being edited private PsiJavaCodeReferenceElement referenceElement; private VirtualFile editBuildFile; private VirtualFile editSourceFile; private BuckTarget editSourceTarget; private BuckTarget editTarget; private Module editModule; // Fields pertaining to the dependency that should be resolved/imported private PsiClass psiClass; private VirtualFile importBuildFile; private VirtualFile importSourceFile; private BuckTarget importSourceTarget; private BuckTarget importTarget; private Module importModule; BuckAddDependencyIntention( Project project, PsiJavaCodeReferenceElement referenceElement, VirtualFile editBuildFile, VirtualFile editSourceFile, BuckTarget editSourceTarget, Module editModule, PsiClass psiClass, VirtualFile importBuildFile, VirtualFile importSourceFile, BuckTarget importSourceTarget, Module importModule) { this.project = project; this.referenceElement = referenceElement; this.editBuildFile = editBuildFile; this.editSourceFile = editSourceFile; this.editSourceTarget = editSourceTarget; this.editModule = editModule; this.psiClass = psiClass; this.importBuildFile = importBuildFile; this.importSourceFile = importSourceFile; this.importSourceTarget = importSourceTarget; this.importModule = importModule; String message = "Add BUCK dependency on owner(" + importSourceTarget + ")"; setText(message); } @Nls(capitalization = Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return this.getClass().getSimpleName(); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { return true; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { String msg = "Invoked for project " + project.getName() + " and file " + psiFile.getName(); LOGGER.info(msg); queryBuckForTargets(editor); } /** Helper class to handle deserialization of buck query. */ static class TargetMetadata { public BuckTarget target; public @Nullable List deps; public @Nullable List visibility; // null means PUBLIC public @Nullable List srcs; public @Nullable List resources; static TargetMetadata from( BuckTargetLocator buckTargetLocator, BuckTarget target, JsonObject payload) { TargetMetadata targetMetadata = new TargetMetadata(); targetMetadata.target = target; targetMetadata.srcs = stringListOrNull(payload.get("srcs")); targetMetadata.resources = stringListOrNull(payload.get("resources")); // Deps are a list of BuckTargets targetMetadata.deps = Optional.ofNullable(stringListOrNull(payload.get("deps"))) .map( deps -> deps.stream() .map( s -> BuckTarget.parse(s).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList())) .orElse(null); // Visibilility falls in one of three cases: // (1) if unspecified => means visibility is limited to the current package // (2) contains "PUBLIC" => available everywhere // (3) otherwise is a list of buck target patterns where it is visible List optionalVisibility = stringListOrNull(payload.get("visibility")); if (optionalVisibility == null) { targetMetadata.visibility = Collections.singletonList(target.asPattern().asPackageMatchingPattern()); } else if (optionalVisibility.contains("PUBLIC")) { targetMetadata.visibility = null; // } else { targetMetadata.visibility = optionalVisibility .stream() .map(p -> BuckTargetPattern.parse(p).map(buckTargetLocator::resolve).orElse(null)) .collect(Collectors.toList()); } return targetMetadata; } static @Nullable List stringListOrNull(@Nullable JsonElement jsonElement) { if (jsonElement == null) { return null; } return new Gson().fromJson(jsonElement, new TypeToken>() {}.getType()); } boolean isVisibleTo(BuckTarget target) { if (visibility == null) { return true; } return visibility.stream().anyMatch(pattern -> pattern.matches(target)); } boolean hasDependencyOn(BuckTarget target) { return deps.stream().anyMatch(dep -> dep.equals(target)); } boolean contains(BuckTarget targetFile) { if (!target.asPattern().asPackageMatchingPattern().matches(targetFile)) { return false; } String relativeToBuildFile = targetFile.getRuleName(); return srcs.contains(relativeToBuildFile) || resources.contains(relativeToBuildFile); } } /** Queries buck for targets that own the editSourceFile and the importSourceFile. */ private void queryBuckForTargets(Editor editor) { BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project); String editPath = editSourceFile.getPath(); String importPath = importSourceFile.getPath(); BuckJsonCommandHandler> handler = new BuckJsonCommandHandler<>( project, BuckCommand.QUERY, new Callback>() { @Override public List deserialize(JsonElement jsonElement) throws IOException { Type type = new TypeToken>() {}.getType(); Map raw = new Gson().fromJson(jsonElement, type); List results = new ArrayList<>(); for (Entry entry : raw.entrySet()) { BuckTarget.parse(entry.getKey()) .map(buckTargetLocator::resolve) .map( target -> TargetMetadata.from(buckTargetLocator, target, entry.getValue())) .ifPresent(results::add); } return results; } @Override public void onSuccess(List results, String stderr) { List editTargets = new ArrayList<>(); List importTargets = new ArrayList<>(); for (TargetMetadata targetMetadata : results) { if (targetMetadata.contains(editSourceTarget)) { editTargets.add(targetMetadata); } if (targetMetadata.contains(importSourceTarget)) { importTargets.add(targetMetadata); } } updateDependencies(editor, editTargets, importTargets); } @Override public void onFailure( String stdout, String stderr, @Nullable Integer exitCode, @Nullable Throwable throwable) { BuckNotification.getInstance(project) .showWarningBalloon( "Could not determine owners for " + editSourceFile + " and/or " + importSourceFile); return; } }); handler .command() .addParameters( "owner(%s)", editPath, importPath, "--output-attributes=deps|srcs|visibility|resources"); handler.runInCurrentThreadPostEnd(() -> {}); } /** * Implementation of {@link * com.intellij.notification.NotificationListener#hyperlinkUpdate(Notification, HyperlinkEvent)}. */ private void hyperlinkActivated( @NotNull Notification notification, @NotNull HyperlinkEvent event) { String href = event.getDescription(); switch (href) { case "editTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(editTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "editBuildFile": FileEditorManager.getInstance(project).openFile(editBuildFile, true); break; case "editSourceFile": FileEditorManager.getInstance(project).openFile(editSourceFile, true); break; case "importTarget": if (BuckTargetLocator.getInstance(project) .findElementForTarget(importTarget) .filter(target -> target instanceof NavigatablePsiElement) .map(target -> (NavigatablePsiElement) target) .filter(Navigatable::canNavigate) .map( e -> { e.navigate(true); return true; }) .orElse(false)) { break; } // fallthrough case "importBuildFile": FileEditorManager.getInstance(project).openFile(importBuildFile, true); break; case "importSourceFile": FileEditorManager.getInstance(project).openFile(importSourceFile, true); break; } } private void updateDependencies( Editor editor, List editTargets, List importTargets) { if (editTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + editSourceTarget + " in " + editBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (importTargets.size() == 0) { String message = "Add dependency failed: Couldn't determine a Buck owner for " + importSourceTarget + " in " + importBuildFile.getPath() + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } TargetMetadata editTargetMetadata = editTargets.get(0); TargetMetadata importTargetMetadata = importTargets.get(0); editTarget = editTargetMetadata.target; importTarget = importTargetMetadata.target; if (!importTargetMetadata.isVisibleTo(editTarget)) { String message = "Add dependency failed: The target " + importTarget + " is not visible to " + editTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } if (!editTargetMetadata.hasDependencyOn(importTarget)) { if (!BuckDeps.modifyTargetToAddDependency( editBuildFile, editTarget.toString(), importTarget.toString())) { String message = "Add dependency failed: Could not add modify build file for " + editTarget + " to add dependency on " + importTarget + ""; BuckNotification.getInstance(project).showErrorBalloon(message, this::hyperlinkActivated); return; } } else { String message = "No need to modify build file " + editBuildFile + ", already has dependency from " + editTarget + " to " + importTarget + ""; BuckNotification.getInstance(project).showInfoBalloon(message, this::hyperlinkActivated); } ModuleRootModificationUtil.updateModel( editModule, (modifiableRootModel -> { if (modifiableRootModel.findModuleOrderEntry(importModule) != null) { LOGGER.info( "No need to modify module " + editModule.getName() + ", already has dependency on " + importModule.getName()); } else { modifiableRootModel.addModuleOrderEntry(importModule); LOGGER.info( "Successfully added module dependency from " + editModule.getName() + " on " + importModule.getName()); } new AddImportAction(project, referenceElement, editor, psiClass).execute(); })); } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 14580 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/autodeps/BuckAddDependencyIntention.java/#L66-L480 | 1 | 2472 | 14580 | minor |
| 518 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 5378 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 | 2 | 518 | 5378 | minor |
| 863 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented-out code 4. Magic numbers 5. Low cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExecutorTransfer { private static final Logger LOG = LoggerFactory.getLogger(ExecutorTransfer.class); private final WorkerState workerData; private final KryoTupleSerializer serializer; private final boolean isDebug; private int indexingBase = 0; private ArrayList localReceiveQueues; // [taskId-indexingBase] => queue : List of all recvQs local to this worker private AtomicReferenceArray queuesToFlush; // [taskId-indexingBase] => queue, some entries can be null. : outbound Qs for this executor instance public ExecutorTransfer(WorkerState workerData, Map topoConf) { this.workerData = workerData; this.serializer = new KryoTupleSerializer(topoConf, workerData.getWorkerTopologyContext()); this.isDebug = ObjectReader.getBoolean(topoConf.get(Config.TOPOLOGY_DEBUG), false); } // to be called after all Executor objects in the worker are created and before this object is used public void initLocalRecvQueues() { Integer minTaskId = workerData.getLocalReceiveQueues().keySet().stream().min(Integer::compareTo).get(); this.localReceiveQueues = Utils.convertToArray(workerData.getLocalReceiveQueues(), minTaskId); this.indexingBase = minTaskId; this.queuesToFlush = new AtomicReferenceArray(localReceiveQueues.size()); } // adds addressedTuple to destination Q if it is not full. else adds to pendingEmits (if its not null) public boolean tryTransfer(AddressedTuple addressedTuple, Queue pendingEmits) { if (isDebug) { LOG.info("TRANSFERRING tuple {}", addressedTuple); } JCQueue localQueue = getLocalQueue(addressedTuple); if (localQueue != null) { return tryTransferLocal(addressedTuple, localQueue, pendingEmits); } return workerData.tryTransferRemote(addressedTuple, pendingEmits, serializer); } // flushes local and remote messages public void flush() throws InterruptedException { flushLocal(); workerData.flushRemotes(); } private void flushLocal() throws InterruptedException { for (int i = 0; i < queuesToFlush.length(); i++) { JCQueue q = queuesToFlush.get(i); if (q != null) { q.flush(); queuesToFlush.set(i, null); } } } public JCQueue getLocalQueue(AddressedTuple tuple) { if ((tuple.dest - indexingBase) >= localReceiveQueues.size()) { return null; } return localReceiveQueues.get(tuple.dest - indexingBase); } /** * Adds tuple to localQueue (if overflow is empty). If localQueue is full adds to pendingEmits instead. pendingEmits can be null. * Returns false if unable to add to localQueue. */ public boolean tryTransferLocal(AddressedTuple tuple, JCQueue localQueue, Queue pendingEmits) { workerData.checkSerialize(serializer, tuple); if (pendingEmits != null) { if (pendingEmits.isEmpty() && localQueue.tryPublish(tuple)) { queuesToFlush.set(tuple.dest - indexingBase, localQueue); return true; } else { pendingEmits.add(tuple); return false; } } else { return localQueue.tryPublish(tuple); } } } |
blob | Long method2 Feature envy3 Commented-out code4 Magic numbers5 Low cohesion | t | f | f | . Long method2. Feature envy3. Commented-out code4. Magic numbers5. Low cohesion | blob | 0 | 7912 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/executor/ExecutorTransfer.java/#L30-L113 | 2 | 863 | 7912 | minor |
| 761 | YES I found bad smells.The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7110 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 2 | 761 | 7110 | major |
| 1715 | {"message":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | "YES I found bad smells","bad smells are" | t | f | f | "YES I found bad smells", "bad smells are" | blob | 0 | 11779 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 1 | 1715 | 11779 | critical |
| 498 | { "NO, I did not find any bad smell" : "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 5045 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 1 | 498 | 5045 | minor |
| 1963 | { "message": "YES I found bad smells", "detected_bad_smells": { "1. Long Method": {}, "2. Blob": {} } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
feature envy | 1. long method: , 2. blob: | t | t | f | 1. long method: , 2. blob: | feature envy | 0 | 12587 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1963 | 12587 | minor |
| 2639 | . NO, I did not find any bad smells | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 15142 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2639 | 15142 | minor | ||
| 2899 | { "input": { "codeSmellsToCheck": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "javaCode": "public class Example { private int calculateSomething(int a, int b) { int result = a + b; if (result > 100) { return 100; } else { return result; } } private void printResult(int result) { System.out.println(result); } }" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | message: yes i found bad smells, detectedcodesmells: long method | t | t | f | message: yes i found bad smells, detectedcodesmells: long method | data class | 0 | 2138 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 1 | 2899 | 2138 | minor |
| 1556 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public abstract class AbstractEntitiesRuntimeModule extends DefaultXbaseRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/xtext/idea/example/entities/Entities.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.idea.example.entities.Entities"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("entities"); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class bindIGrammarAccess() { return EntitiesGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISemanticSequencer() { return EntitiesSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISyntacticSequencer() { return EntitiesSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIParser() { return EntitiesParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIAntlrTokenFileProvider() { return EntitiesAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindLexer() { return InternalEntitiesLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider provideInternalEntitiesLexer() { return LexerProvider.create(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class bindEntitiesValidator() { return EntitiesValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public Class bindIBatchScopeProvider() { return EntitiesScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIScopeProviderDelegate(Binder binder) { binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(XImportSectionNamespaceScopeProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIgnoreCaseLinking(Binder binder) { binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIContainer$Manager() { return StateBasedContainerManager.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIAllContainersState$Provider() { return ResourceSetBasedAllContainersStateProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptions(Binder binder) { binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptionsPersisted(Binder binder) { binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class bindIFormatter2() { return EntitiesFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIQualifiedNameProvider() { return XbaseQualifiedNameProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindILocationInFileProvider() { return JvmLocationInFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIGlobalScopeProvider() { return TypesAwareDefaultGlobalScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindFeatureNameValidator() { return LogicalContainerAwareFeatureNameValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultBatchTypeResolver() { return LogicalContainerAwareBatchTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultReentrantTypeResolver() { return LogicalContainerAwareReentrantTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIResourceValidator() { return DerivedStateAwareResourceValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIJvmModelInferrer() { return EntitiesJvmModelInferrer.class; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11283 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities/src-gen/org/eclipse/xtext/idea/example/entities/AbstractEntitiesRuntimeModule.java/#L76-L249 | 2 | 1556 | 11283 | minor |
| 1903 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Lack of encapsulation 5. Complex conditional statements 6. Unnecessary comments 7. Poor exception handling 8. Bloated constructor 9. Inconsistent variable naming 10. Mixing of different responsibilities in one class 11. Unused import statements 12. Unnecessary String conversions 13. Missing access modifiers 14. Magic numbers 15. Violation of Single Responsibility Principle 16. Hard-coding of default values 17. Inefficient property retrieval methods 18. Unused methods 19. Mixing of different styles of coding 20. Violation of Open-Closed Principle | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
blob | Long method2 Feature envy3 Duplicate code 4 Lack of encapsulation 5 Complex conditional statements 6 Unnecessary comments 7 Poor exception handling 8 Bloated constructor 9 Inconsistent variable naming | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Lack of encapsulation 5. Complex conditional statements 6. Unnecessary comments 7. Poor exception handling 8. Bloated constructor 9. Inconsistent variable naming | blob | 0 | 12365 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 1903 | 12365 | major |
| 138 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportsAwareClipboardAction extends TextEditorAction { public static class Factory implements IClipboardActionFactory { @Inject private MembersInjector injector; @Override public TextEditorAction create(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) { ImportsAwareClipboardAction action = new ImportsAwareClipboardAction(bundle, prefix, editor, operationCode); injector.injectMembers(action); return action; } } private static final XbaseClipboardTransfer TRANSFER_INSTANCE = new XbaseClipboardTransfer(); private final int operationCode; private ITextOperationTarget textOperationTarget; private @Inject ImportsUtil importsUtil; /** * Creates the action. * * @param bundle * the resource bundle * @param prefix * a prefix to be prepended to the various resource keys (described in ResourceAction * constructor), or null if none * @param editor * the text editor. May not be null. * @param operationCode * the operation code */ public ImportsAwareClipboardAction(ResourceBundle bundle, String prefix, ITextEditor editor, final int operationCode) { super(bundle, prefix, editor); this.operationCode = operationCode; if (operationCode == ITextOperationTarget.CUT) { setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); } else if (operationCode == ITextOperationTarget.COPY) { setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); } else if (operationCode == ITextOperationTarget.PASTE) { setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); } else { Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$ } update(); } protected void internalDoOperation() { if (operationCode == ITextOperationTarget.PASTE) { doPasteWithImportsOperation(); } else { doCutCopyWithImportsOperation(); } } private void doCutCopyWithImportsOperation() { try { final XbaseClipboardData cbData = createClipboardData(); if (cbData != null ) { ClipboardUtil.clipboardOperation(new Function() { @Override public Boolean apply(Clipboard clipboard) { Map payload = newLinkedHashMap(); payload.put(cbData, TRANSFER_INSTANCE); TextTransfer textTransfer = TextTransfer.getInstance(); String textData = (String) clipboard.getContents(textTransfer); if (textData == null || textData.isEmpty()) { // StyledText copied any data to ClipBoard return Boolean.FALSE; } payload.put(textData, textTransfer); RTFTransfer rtfTransfer = RTFTransfer.getInstance(); String rtfData = (String) clipboard.getContents(rtfTransfer); if (rtfData != null && !rtfData.isEmpty()) { payload.put(rtfData, rtfTransfer); } List datas = newArrayList(); List dataTypes = newArrayList(); for (Entry entry : payload.entrySet()) { datas.add(entry.getKey()); dataTypes.add(entry.getValue()); } try { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } return Boolean.FALSE; } } }); } } finally { textOperationTarget.doOperation(operationCode); } } private void doPasteWithImportsOperation() { XbaseClipboardData xbaseClipboardData = ClipboardUtil .clipboardOperation(new Function() { @Override public XbaseClipboardData apply(Clipboard input) { Object content = input.getContents(TRANSFER_INSTANCE); if (content instanceof XbaseClipboardData) { return (XbaseClipboardData) content; } return null; } }); JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent(); String textFromClipboard = ClipboardUtil.getTextFromClipboard(); XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor)); if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) { doPasteXbaseCode(xbaseClipboardData, addImports); } else if (javaImportsContent != null) { doPasteJavaCode(textFromClipboard, javaImportsContent, addImports); } else { textOperationTarget.doOperation(operationCode); } } /** * Should not add imports when pasting into a {@link XStringLiteral} or Comments (except of JavaDoc) * * @param document * - {@link IDocument} to work with * @param caretOffset * - current caret offset */ protected boolean shouldAddImports(IDocument document, int caretOffset) { if (caretOffset == 0) { return true; } String typeRight = IDocument.DEFAULT_CONTENT_TYPE; String typeLeft = IDocument.DEFAULT_CONTENT_TYPE; try { typeRight = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset, false); typeLeft = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset > 0 ? caretOffset - 1 : caretOffset, false); } catch (BadLocationException exception) { // Should not happen } if (COMMENT_PARTITION.equals(typeRight) || STRING_LITERAL_PARTITION.equals(typeRight) || SL_COMMENT_PARTITION.equals(typeRight) || "__rich_string".equals(typeRight)) { if (typeLeft.equals(typeRight)) return false; } return true; } private int caretOffset(final XtextEditor xtextEditor) { ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer(); int caretOffset = sourceViewer.getTextWidget().getCaretOffset(); if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; caretOffset = extension.widgetOffset2ModelOffset(caretOffset); } return caretOffset; } private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(), xbaseClipboardData.getExtensionImports(), getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(), new String[] {}, getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private boolean sameTarget(XbaseClipboardData xbaseClipboardData) { IEditorInput editorInput = getTextEditor().getEditorInput(); if (editorInput == null) { return false; } return xbaseClipboardData.getSourceIndentifier().equals(editorInput.toString()); } private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.readOnly(new IUnitOfWork() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple, Set, Set> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; } private IXtextDocument getXtextDocument() { XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); IXtextDocument document = xtextEditor.getDocument(); return document; } @Override public void update() { super.update(); if (isModifyOperation() && !canModifyEditor()) { setEnabled(false); return; } ITextEditor editor = getTextEditor(); if (textOperationTarget == null && editor != null) textOperationTarget = editor.getAdapter(ITextOperationTarget.class); boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode())); setEnabled(isEnabled); } private int getOperationCode() { return operationCode; } @Override public void run() { if (textOperationTarget == null) return; ITextEditor editor = getTextEditor(); if (editor == null) return; if (isModifyOperation() && !validateEditorInputState()) return; BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { internalDoOperation(); } }); } private boolean isModifyOperation() { return operationCode != ITextOperationTarget.COPY; } private Shell getShell() { ITextEditor editor = getTextEditor(); if (editor != null) { IWorkbenchPartSite site = editor.getSite(); Shell shell = site.getShell(); if (shell != null && !shell.isDisposed()) { return shell; } } return null; } private Display getDisplay() { Shell shell = getShell(); if (shell != null) { return shell.getDisplay(); } return null; } @Override public void setEditor(ITextEditor editor) { super.setEditor(editor); this.textOperationTarget = null; } public static final class XbaseClipboardData { private String sourceIndentifier; private String[] imports; private String[] staticImports; private String[] extensionImports; public XbaseClipboardData(String sourceIndentifier, String[] imports, String[] staticImports, String[] extensionImports) { this.sourceIndentifier = sourceIndentifier; this.imports = imports; this.staticImports = staticImports; this.extensionImports = extensionImports; } public XbaseClipboardData(byte[] bytes) throws IOException { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes)); try { sourceIndentifier = dataIn.readUTF(); imports = readArray(dataIn); staticImports = readArray(dataIn); extensionImports = readArray(dataIn); } finally { dataIn.close(); } } protected final String[] readArray(DataInputStream dataIn) throws IOException { int count = dataIn.readInt(); String[] array = new String[count]; for (int i = 0; i < count; i++) { array[i] = dataIn.readUTF(); } return array; } public byte[] serialize() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); try { dataOut.writeUTF(sourceIndentifier); writeArray(dataOut, imports); writeArray(dataOut, staticImports); writeArray(dataOut, extensionImports); } finally { dataOut.close(); out.close(); } return out.toByteArray(); } protected final void writeArray(DataOutputStream dataOut, String[] array) throws IOException { dataOut.writeInt(array.length); for (int i = 0; i < array.length; i++) { dataOut.writeUTF(array[i]); } } public String getSourceIndentifier() { return sourceIndentifier; } public String[] getImports() { return imports; } public String[] getStaticImports() { return staticImports; } public String[] getExtensionImports() { return extensionImports; } } private static class XbaseClipboardTransfer extends ByteArrayTransfer { private static final String TYPE_NAME = "xbase-source-with-imports-transfer-format"; private static final int TYPEID = registerType(TYPE_NAME); @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object data, TransferData transferData) { if (data instanceof XbaseClipboardData) { try { super.javaToNative(((XbaseClipboardData) data).serialize(), transferData); } catch (IOException e) { //it's best to send nothing if there were problems } } } @Override protected Object nativeToJava(TransferData transferData) { byte[] bytes = (byte[]) super.nativeToJava(transferData); if (bytes != null) { try { return new XbaseClipboardData(bytes); } catch (IOException e) { } } return null; } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 1747 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xbase.ui/src/org/eclipse/xtext/xbase/ui/editor/actions/ImportsAwareClipboardAction.java/#L79-L520 | 1 | 138 | 1747 | minor |
| 3248 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 5487 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 3248 | 5487 | major |
| 192 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class FuncLongToString extends VectorExpression { private static final long serialVersionUID = 1L; private final int inputColumn; // Transient members initialized by transientInit method. protected byte[] bytes; FuncLongToString(int inputColumn, int outputColumnNum) { super(outputColumnNum); this.inputColumn = inputColumn; } FuncLongToString() { super(); // Dummy final assignments. inputColumn = -1; } @Override public void transientInit() throws HiveException { super.transientInit(); bytes = new byte[64]; // staging area for results, to avoid new() calls } @Override public void evaluate(VectorizedRowBatch batch) throws HiveException { if (childExpressions != null) { super.evaluateChildren(batch); } LongColumnVector inputColVector = (LongColumnVector) batch.cols[inputColumn]; int[] sel = batch.selected; int n = batch.size; long[] vector = inputColVector.vector; BytesColumnVector outputColVector = (BytesColumnVector) batch.cols[outputColumnNum]; outputColVector.initBuffer(); boolean[] inputIsNull = inputColVector.isNull; boolean[] outputIsNull = outputColVector.isNull; if (n == 0) { //Nothing to do return; } // We do not need to do a column reset since we are carefully changing the output. outputColVector.isRepeating = false; if (inputColVector.isRepeating) { if (inputColVector.noNulls || !inputIsNull[0]) { // Set isNull before call in case it changes it mind. outputIsNull[0] = false; prepareResult(0, vector, outputColVector); } else { outputIsNull[0] = true; outputColVector.noNulls = false; } outputColVector.isRepeating = true; return; } if (inputColVector.noNulls) { if (batch.selectedInUse) { // CONSIDER: For large n, fill n or all of isNull array and use the tighter ELSE loop. if (!outputColVector.noNulls) { for(int j = 0; j != n; j++) { final int i = sel[j]; // Set isNull before call in case it changes it mind. outputIsNull[i] = false; prepareResult(i, vector, outputColVector); } } else { for(int j = 0; j != n; j++) { final int i = sel[j]; prepareResult(i, vector, outputColVector); } } } else { if (!outputColVector.noNulls) { // Assume it is almost always a performance win to fill all of isNull so we can // safely reset noNulls. Arrays.fill(outputIsNull, false); outputColVector.noNulls = true; } for(int i = 0; i != n; i++) { prepareResult(i, vector, outputColVector); } } } else /* there are nulls in the inputColVector */ { // Carefully handle NULLs... outputColVector.noNulls = false; if (batch.selectedInUse) { for(int j=0; j != n; j++) { int i = sel[j]; outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } else { for(int i = 0; i != n; i++) { outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } } } /* Evaluate result for position i (using bytes[] to avoid storage allocation costs) * and set position i of the output vector to the result. */ abstract void prepareResult(int i, long[] vector, BytesColumnVector outputColVector); @Override public String vectorExpressionParameters() { return getColumnParamString(0, inputColumn); } @Override public VectorExpressionDescriptor.Descriptor getDescriptor() { return (new VectorExpressionDescriptor.Builder()).setMode( VectorExpressionDescriptor.Mode.PROJECTION).setNumArguments(1).setInputExpressionTypes( VectorExpressionDescriptor.InputExpressionType.COLUMN).setArgumentTypes( VectorExpressionDescriptor.ArgumentType.INT_FAMILY).build(); } } |
blob | data class | t | t | f | data class | blob | 0 | 2216 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/expressions/FuncLongToString.java/#L36-L172 | 1 | 192 | 2216 | minor |
| 1356 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MissedUpdatesFinder extends MissedUpdatesFinderBase { private long ourHighThreshold; // 80th percentile private long ourHighest; // currently just used for logging/debugging purposes private String logPrefix; private long nUpdates; MissedUpdatesFinder(List ourUpdates, String logPrefix, long nUpdates, long ourLowThreshold, long ourHighThreshold) { super(ourUpdates, ourLowThreshold); this.logPrefix = logPrefix; this.ourHighThreshold = ourHighThreshold; this.ourHighest = ourUpdates.get(0); this.nUpdates = nUpdates; } public MissedUpdatesRequest find(List otherVersions, Object updateFrom, Supplier canHandleVersionRanges) { otherVersions.sort(absComparator); if (debug) { log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom); } long otherHigh = percentile(otherVersions, .2f); long otherLow = percentile(otherVersions, .8f); long otherHighest = otherVersions.get(0); if (ourHighThreshold < otherLow) { // Small overlap between version windows and ours is older // This means that we might miss updates if we attempted to use this method. // Since there exists just one replica that is so much newer, we must // fail the sync. log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (ourLowThreshold > otherHigh && ourHighest >= otherHighest) { // Small overlap between windows and ours is newer. // Using this list to sync would result in requesting/replaying results we don't need // and possibly bringing deleted docs back to life. log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); // Because our versions are newer, IndexFingerprint with the remote would not match us. // We return true on our side, but the remote peersync with us should fail. return MissedUpdatesRequest.ALREADY_IN_SYNC; } boolean completeList = otherVersions.size() < nUpdates; MissedUpdatesRequest updatesRequest; if (canHandleVersionRanges.get()) { updatesRequest = handleVersionsWithRanges(otherVersions, completeList); } else { updatesRequest = handleIndividualVersions(otherVersions, completeList); } if (updatesRequest.totalRequestedUpdates > nUpdates) { log.info("{} PeerSync will fail because number of missed updates is more than:{}", logPrefix, nUpdates); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (updatesRequest == MissedUpdatesRequest.EMPTY) { log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); } return updatesRequest; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10769 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/PeerSync.java/#L787-L856 | 1 | 1356 | 10769 | minor |
| 1570 | {"message": "YES I found bad smells", "the bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 11335 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 1570 | 11335 | major |
| 191 | { "response": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | long method | t | t | f | long method | blob | 0 | 2197 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 1 | 191 | 2197 | major |
| 1102 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9840 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1102 | 9840 | minor |
| 2900 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 2146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L233896-L233981 | 2 | 2900 | 2146 | minor | ||
| 3621 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 8146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 1 | 3621 | 8146 | minor | ||
| 109 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1442 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 2 | 109 | 1442 | major |
| 706 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list 5. Duplicated code 6. Divergent change 7. God class 8. Primitive obsession 9. Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method2 Feature envy3 Large class4 Long parameter list5 Duplicated code6 Divergent change7 God class8 Primitive obsession9 Message chains | t | f | f | . Long method2. Feature envy3. Large class4. Long parameter list5. Duplicated code6. Divergent change7. God class8. Primitive obsession9. Message chains | data class | 0 | 6735 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 706 | 6735 | minor |
| 1822 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 12100 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 1 | 1822 | 12100 | minor |
| 2428 | { "message": "YES I found bad smells", "bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class createJob_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createJob_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createJob_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | long method | t | t | f | long method | blob | 0 | 14450 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/AuroraSchedulerManager.java/#L2760-L2805 | 1 | 2428 | 14450 | minor |
| 2501 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractClientProvider { public AbstractClientProvider() { } /** * Generates a fixed format of application tags given one or more of * application name, version and description. This allows subsequent query for * an application with a name only, version only or description only or any * combination of those as filters. * * @param appName name of the application * @param appVersion version of the application * @param appDescription brief description of the application * @return */ public static final Set createApplicationTags(String appName, String appVersion, String appDescription) { Set tags = new HashSet<>(); tags.add(ServiceUtils.createNameTag(appName)); if (appVersion != null) { tags.add(ServiceUtils.createVersionTag(appVersion)); } if (appDescription != null) { tags.add(ServiceUtils.createDescriptionTag(appDescription)); } return tags; } /** * Validate the artifact. * @param artifact */ public abstract void validateArtifact(Artifact artifact, String compName, FileSystem fileSystem) throws IOException; protected abstract void validateConfigFile(ConfigFile configFile, String compName, FileSystem fileSystem) throws IOException; /** * Validate the config files. * @param configFiles config file list * @param fs file system */ public void validateConfigFiles(List configFiles, String compName, FileSystem fs) throws IOException { Set destFileSet = new HashSet<>(); for (ConfigFile file : configFiles) { if (file.getType() == null) { throw new IllegalArgumentException("File type is empty"); } ConfigFile.TypeEnum fileType = file.getType(); if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) { if (StringUtils.isEmpty(file.getSrcFile()) && !file.getProperties().containsKey(CONTENT)) { throw new IllegalArgumentException(MessageFormat.format("For {0} " + "format, either src_file must be specified in ConfigFile," + " or the \"{1}\" key must be specified in " + "the 'properties' field of ConfigFile. ", ConfigFile.TypeEnum.TEMPLATE, CONTENT)); } } else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals( ConfigFile.TypeEnum.ARCHIVE)) { if (!file.getProperties().isEmpty()) { throw new IllegalArgumentException(String .format("For %s format, should not specify any 'properties.'", fileType)); } String srcFile = file.getSrcFile(); if (srcFile == null || srcFile.isEmpty()) { throw new IllegalArgumentException(String.format( "For %s format, should make sure that srcFile is specified", fileType)); } FileStatus fileStatus = fs.getFileStatus(new Path(srcFile)); if (fileStatus != null && fileStatus.isDirectory()) { throw new IllegalArgumentException("srcFile=" + srcFile + " is a directory, which is not supported."); } } if (!StringUtils.isEmpty(file.getSrcFile())) { Path p = new Path(file.getSrcFile()); if (!fs.exists(p)) { throw new IllegalArgumentException( "Specified src_file does not exist on " + fs.getScheme() + ": " + file.getSrcFile()); } } if (StringUtils.isEmpty(file.getDestFile())) { throw new IllegalArgumentException("dest_file is empty."); } if (destFileSet.contains(file.getDestFile())) { throw new IllegalArgumentException( "Duplicated ConfigFile exists: " + file.getDestFile()); } destFileSet.add(file.getDestFile()); java.nio.file.Path destPath = Paths.get(file.getDestFile()); if (!destPath.isAbsolute() && destPath.getNameCount() > 1) { throw new IllegalArgumentException("Non-absolute dest_file has more " + "than one path element"); } // provider-specific validation validateConfigFile(file, compName, fs); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14658 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/AbstractClientProvider.java/#L38-L150 | 2 | 2501 | 14658 | minor |
| 1330 | YES I found bad smells. 1. Feature envy, 2. Magic numbers, 3. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | Feature envy, 2 Magic numbers, 3 Long method | t | f | f | . Feature envy, 2. Magic numbers, 3. Long method | data class | 0 | 10710 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 2 | 1330 | 10710 | minor |
| 1236 | { "output": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class EventAdapterGenerator { public static AdapterClassLoader ldr = new AdapterClassLoader(); static Class EVENTLISTENER = null; static String CLASSPACKAGE = "org/apache/bsf/util/event/adapters/"; static String WRITEDIRECTORY = null; // starting 8 bytes of all Java Class files static byte CLASSHEADER[]; // constant pool items found in all event adapters static short BASECPCOUNT; // number of cp items + 1 ( cp item # 0 reserved for JVM ) static byte BASECP[]; // // some bytes in the middle of the class file (see below) static byte FIXEDCLASSBYTES[]; // the initialization method, noargs constructor static byte INITMETHOD[]; private static BSF_Log logger=null; /* The static initializer */ static { // logger = LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); logger = BSF_LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); String USERCLASSPACKAGE = System.getProperty("DynamicEventClassPackage", ""); if (!USERCLASSPACKAGE.equals("")) { CLASSPACKAGE = USERCLASSPACKAGE; } if(CLASSPACKAGE.length() > 0 ) { CLASSPACKAGE = CLASSPACKAGE.replace('\\','/'); if(!CLASSPACKAGE.endsWith("/")) { CLASSPACKAGE = CLASSPACKAGE+"/"; } } WRITEDIRECTORY = System.getProperty("DynamicEventClassWriteDirectory",CLASSPACKAGE); if(WRITEDIRECTORY.length() > 0 ) { WRITEDIRECTORY = WRITEDIRECTORY.replace('\\','/'); if(!WRITEDIRECTORY.endsWith("/")) { WRITEDIRECTORY = WRITEDIRECTORY+"/"; } } try // { EVENTLISTENER = Class.forName("java.util.EventListener"); } { // EVENTLISTENER = Thread.currentThread().getContextClassLoader().loadClass ("java.util.EventListener"); // rgf, 2006-01-05 // rgf, 20070917: first try context class loader, then BSFManager's defining class loader EVENTLISTENER=null; ClassLoader tccl=Thread.currentThread().getContextClassLoader(); if (tccl!=null) { try { EVENTLISTENER = tccl.loadClass ("java.util.EventListener"); } catch(ClassNotFoundException ex01) {} } if (EVENTLISTENER==null) // did not work, try to load it via the definedClassLoader { EVENTLISTENER = BSFManager.getDefinedClassLoader().loadClass ("java.util.EventListener"); } } catch(ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // start of the Java Class File CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xCA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xFE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)3); // minor version CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)45); // major version // Start the constant pool for base items in all event adapter classes BASECPCOUNT = 17; // number of cp items + 1 ( cp item # 0 reserved for JVM ) // cp item 01 BASECP = Bytecode.addUtf8(BASECP,"()V"); // cp item 02 BASECP = Bytecode.addUtf8(BASECP,""); // cp item 03 BASECP = Bytecode.addUtf8(BASECP,"Code"); // cp item 04 BASECP = Bytecode.addUtf8(BASECP,"eventProcessor"); // cp item 05 BASECP = Bytecode.addUtf8(BASECP,"java/lang/Object"); // cp item 06 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventAdapterImpl"); // cp item 07 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventProcessor"); // cp item 08 BASECP = Bytecode.addUtf8(BASECP,"(Ljava/lang/String;[Ljava/lang/Object;)V"); // cp item 09 BASECP = Bytecode.addUtf8(BASECP,"Lorg/apache/bsf/util/event/EventProcessor;"); // cp item 10 BASECP = Bytecode.addClass(BASECP,(short)5); // Class "java/lang/Object" // cp item 11 BASECP = Bytecode.addClass(BASECP,(short)6); // Class "org/apache/bsf/util/event/EventAdapterImpl" // cp item 12 BASECP = Bytecode.addClass(BASECP,(short)7); // Class "org/apache/bsf/util/event/EventProcessor" // cp item 13 BASECP = Bytecode.addNameAndType(BASECP,(short)2,(short)1); // "" "()V" // cp item 14 BASECP = Bytecode.addNameAndType(BASECP,(short)4,(short)9); // "eventProcessor" "Lorg/apache/bsf/util/event/EventProcessor;" // cp item 15 BASECP = Bytecode.addFieldRef(BASECP,(short)11,(short)14); // cp item 16 BASECP = Bytecode.addMethodRef(BASECP,(short)11,(short)13); // fixed bytes in middle of class file FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0x21); // access_flags (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)20); // this_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)11); // super_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)1); // interface_count (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)19); // interfaces (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0); // field_count (fixed) // initialization method, constructor INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // access_flags INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)2); // name_index "" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // descriptor_index "()V" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // attribute_count INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)3); // attribute_name_index "Code" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)17); // attribute_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_stack INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_locals INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)5); // code_length //code INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0x2A); // aload_0 INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB7); // invokespecial INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)16); // method_ref index INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB1); // return // exception table INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // exception_table_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // attributes_count } /* methods that take an EventListener Class Type to create an EventAdapterClass */ public static Class makeEventAdapterClass(Class listenerType,boolean writeClassFile) { logger.debug("EventAdapterGenerator"); if( EVENTLISTENER.isAssignableFrom(listenerType) ) { boolean exceptionable = false; boolean nonExceptionable = false; byte constantPool[] = null; short cpBaseIndex; short cpCount = 0; short cpExceptionBaseIndex; short exceptionableCount; short nonExceptionableCount; /* Derive Names */ String listenerTypeName = listenerType.getName(); logger.debug("ListenerTypeName: "+listenerTypeName); String adapterClassName = CLASSPACKAGE+ (listenerTypeName.endsWith("Listener") ? listenerTypeName.substring(0, listenerTypeName.length() - 8) : listenerTypeName).replace('.', '_') + "Adapter"; String finalAdapterClassName = adapterClassName; Class cached = null; int suffixIndex = 0; do { if (null != (cached = ldr.getLoadedClass(finalAdapterClassName))) { logger.debug("cached: "+cached); try { if (!listenerType.isAssignableFrom(cached)) finalAdapterClassName = adapterClassName + "_" + suffixIndex++; else return cached; } catch(VerifyError ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); return cached; } } } while (cached != null); String eventListenerName = listenerTypeName.replace('.', '/'); /* method stuff */ java.lang.reflect.Method lms[] = listenerType.getMethods(); /* ****************************************************************************************** */ // Listener interface // Class name cpCount += 4; // cp item 17 constantPool = Bytecode.addUtf8(constantPool,eventListenerName); // cp item 18 constantPool = Bytecode.addUtf8(constantPool,finalAdapterClassName); // cp item 19 constantPool = Bytecode.addClass(constantPool,(short)17); // cp item 20 constantPool = Bytecode.addClass(constantPool,(short)18); // do we have nonExceptionalble event, exceptionable or both for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); if( 0 < exceptionTypes.length) { exceptionable = true; } else { nonExceptionable = true; } }/* End for*/ /* ****************************************************************************************** */ // optional inclusion of nonexceptional events affects exceptional events indices nonExceptionableCount = 0; if(nonExceptionable) { nonExceptionableCount = 3; cpCount += nonExceptionableCount; // cp item 21 constantPool = Bytecode.addUtf8(constantPool,"processEvent"); // cp item 22 constantPool = Bytecode.addNameAndType(constantPool,(short)21,(short)8); // cp item 23 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)22); } /* ****************************************************************************************** */ // optional inclusion of exceptional events affects CP Items which follow for specific methods exceptionableCount = 0; if(exceptionable) { int classIndex = BASECPCOUNT + cpCount + 1; int nameIndex = BASECPCOUNT + cpCount + 0; int natIndex = BASECPCOUNT + cpCount + 3; exceptionableCount = 5; cpCount += exceptionableCount; // cp item 24 or 21 constantPool = Bytecode.addUtf8(constantPool,"processExceptionableEvent"); // cp item 25 or 22 constantPool = Bytecode.addUtf8(constantPool,"java/lang/Exception"); // cp item 26 or 23 constantPool = Bytecode.addClass(constantPool,(short)classIndex); // cp item 27 or 24 constantPool = Bytecode.addNameAndType(constantPool,(short)nameIndex,(short)8); // cp item 28 or 25 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)natIndex); } // base index for method cp references cpBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpBaseIndex: " + cpBaseIndex); for (int i = 0 ; i < lms.length ; ++i) { String eventMethodName = lms[i].getName(); String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); cpCount += 3; // cp items for event methods constantPool = Bytecode.addUtf8(constantPool,eventMethodName); constantPool = Bytecode.addUtf8(constantPool,("(L" + eventName + ";)V")); constantPool = Bytecode.addString(constantPool,(short)(BASECPCOUNT+cpCount-3)); }/* End for*/ boolean propertyChangeFlag[] = new boolean[lms.length]; int cpIndexPCE = 0; for (int i = 0 ; i < lms.length ; ++i) { String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); // cp items for PropertyChangeEvent special handling if(eventName.equalsIgnoreCase("java/beans/PropertyChangeEvent")) { propertyChangeFlag[i] = true; if( 0 == cpIndexPCE ) { constantPool = Bytecode.addUtf8(constantPool,eventName); constantPool = Bytecode.addUtf8(constantPool,"getPropertyName"); constantPool = Bytecode.addUtf8(constantPool,"()Ljava/lang/String;"); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT + cpCount)); constantPool = Bytecode.addNameAndType(constantPool, (short)(BASECPCOUNT + cpCount + 1), (short)(BASECPCOUNT + cpCount + 2)); constantPool = Bytecode.addMethodRef(constantPool, (short)(BASECPCOUNT + cpCount + 3), (short)(BASECPCOUNT + cpCount + 4)); cpCount += 6; cpIndexPCE = BASECPCOUNT + cpCount - 1; } } else { propertyChangeFlag[i] = false; } }/* End for*/ cpExceptionBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpExceptionBaseIndex: " + cpExceptionBaseIndex); int excpIndex[][] = new int[lms.length][]; for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); excpIndex[i] = new int[exceptionTypes.length]; for ( int j = 0 ; j < exceptionTypes.length ; j++) { constantPool = Bytecode.addUtf8(constantPool,exceptionTypes[j].getName().replace('.', '/')); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT+cpCount)); excpIndex[i][j] = BASECPCOUNT + cpCount + 1; cpCount += 2; } }/* End for*/ /* end constant pool */ /* ************************************************************************************************ */ // put the Class byte array together /* start */ byte newClass[] = CLASSHEADER; // magic, version (fixed) short count = (short)(BASECPCOUNT + cpCount); newClass = ByteUtility.addBytes(newClass,count); // constant_pool_count (variable) newClass = ByteUtility.addBytes(newClass,BASECP); // constant_pool (fixed) newClass = ByteUtility.addBytes(newClass,constantPool); // constant_pool (variable) newClass = ByteUtility.addBytes(newClass,FIXEDCLASSBYTES); // see FIXEDCLASSBYTES (fixed) newClass = ByteUtility.addBytes(newClass,(short)(lms.length+1)); // method_count (variable) newClass = ByteUtility.addBytes(newClass,INITMETHOD); // constructor (fixed) // methods /* ****************************************************************************************** */ /* loop over listener methods from listenerType */ for (int i = 0 ; i < lms.length ; ++i) { newClass = ByteUtility.addBytes(newClass,(short)1); // access_flags (fixed) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+0)); // name_index (variable) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+1)); // descriptor_index (variable) newClass = ByteUtility.addBytes(newClass,(short)1); // attribute_count (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // attribute_name_index code(fixed) // Code Attribute Length int length = 32; if( 0 < excpIndex[i].length ) { length += 5 + 8 * ( 1 + excpIndex[i].length ); } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // attribute_length (variable) // start code attribute newClass = ByteUtility.addBytes(newClass,(short)6); // max_stack (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // max_locals (fixed) // Code Length length = 20; if(exceptionable && 0 < excpIndex[i].length) { length += 5; } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // code_length (variable) // start code newClass = ByteUtility.addBytes(newClass,(byte)0x2A); // aload_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB4); // getfield (fixed) newClass = ByteUtility.addBytes(newClass,(short)15); // index (fixed) if(propertyChangeFlag[i]) { // the propertyName is passed as the first parameter newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB6); // invokevirtual (fixed) newClass = ByteUtility.addBytes(newClass,(short)cpIndexPCE); // methodref (variable) } else { // the eventMethodName is passed as the first parameter // Target for method invocation. newClass = ByteUtility.addBytes(newClass,(byte)0x12); // ldc (fixed) newClass = ByteUtility.addBytes(newClass,(byte)(cpBaseIndex+3*i+2)); // index (byte) (variable) } newClass = ByteUtility.addBytes(newClass,(byte)0x04); // iconst_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBD); // anewarray (fixed) newClass = ByteUtility.addBytes(newClass,(short)10); // Class java/lang/Object (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x59); // dup (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x53); // aastore (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB9); // invokeinterface (fixed) // index to processEvent or processExceptionableEvent method length = 23; // actually an index into cp if(exceptionable && nonExceptionable) { // interface method index if( 0 < lms[i].getExceptionTypes().length ) { length += 5; } } else if(exceptionable) { length += 2; } newClass = ByteUtility.addBytes(newClass,(short)length); // index (process??????...) (variable) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x00); // noop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) if(exceptionable && 0 < excpIndex[i].length) { // exception code newClass = ByteUtility.addBytes(newClass,(byte)0x4D); // astore_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2C); // aload_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBF); // athrow (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x57); // pop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) // end code // exception table length = excpIndex[i].length; newClass = ByteUtility.addBytes(newClass,(short)(1+length)); // exception_table_length (variable) for( int j = 0 ; j < length ; j++ ) { // catch exception types and rethrow newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)22); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)20); // handler_pc (fixed) } newClass = ByteUtility.addBytes(newClass,(short)excpIndex[i][j]); // catch_type (variable) } // catch "exception" and trap it newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)25); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)23); // handler_pc (fixed) } if(nonExceptionable) { newClass = ByteUtility.addBytes(newClass,(short)26); } // catch_type (fixed) else // or { newClass = ByteUtility.addBytes(newClass,(short)23); } // catch_type (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)0); } // exception_table_length (fixed) // attributes on the code attribute (none) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) // end code attribute }/* End for*/ // Class Attributes (none for this) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) /* done */ logger.debug("adapterName: " + finalAdapterClassName); logger.debug("cpCount: " + count + " = " + BASECPCOUNT + " + " + cpCount); logger.debug("methodCount: " + (lms.length+1)); // output to disk class file /* ****************************************************************************************** */ // now create the class and load it // return the Class. if (writeClassFile) { try { // removed "WRITEDIRECTORY+", as this path is already part of 'finalAdapterClassName' FileOutputStream fos = new FileOutputStream(finalAdapterClassName+".class"); fos.write(newClass); fos.close(); } catch(IOException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { Class ret = ldr.loadClass(finalAdapterClassName); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } try { Class ret = ldr.defineClass(finalAdapterClassName,newClass); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch(Throwable ex) // rgf, 2012-01-15 { System.err.println(ex.getMessage()); ex.printStackTrace(); } } return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10389 | https://github.com/apache/commons-bsf/blob/88b2601a3caecc32aba38f2b3980d646e9a1b698/src/main/java/org/apache/bsf/util/event/generator/EventAdapterGenerator.java/#L46-L606 | 2 | 1236 | 10389 | major |
| 2496 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Empty catch block 4. Boolean trap (conf.getBoolean used to check for an operation) 5. Comments describing what a method should do instead of just doing it 6. Primitive obsession (using strings for host and port values instead of a proper data structure) 7. Magic numbers (use of hardcoded values for server configuration) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | Long method2 Feature envy3 Empty catch block4 Boolean trap (confgetBoolean used to check for an operation)5 Comments describing what a method should do instead of just doing it6 Primitive obsession (using strings for host and port values instead of a proper data structure)7 Magic numbers (use of hardcoded values for server configuration) | t | f | f | . Long method2. Feature envy3. Empty catch block4. Boolean trap (conf.getBoolean used to check for an operation)5. Comments describing what a method should do instead of just doing it6. Primitive obsession (using strings for host and port values instead of a proper data structure)7. Magic numbers (use of hardcoded values for server configuration) | data class | 0 | 14641 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2496 | 14641 | minor |
| 427 | YES I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToCollectionConverter(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Collection.class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService .canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Collection target = createCollection(targetType, elementDescriptor, elements.length); Stream stream = Arrays.stream(elements).map(String::trim); if (elementDescriptor != null) { stream = stream.map((element) -> this.conversionService.convert(element, sourceType, elementDescriptor)); } stream.forEach(target::add); return target; } private Collection createCollection(TypeDescriptor targetType, TypeDescriptor elementDescriptor, int length) { return CollectionFactory.createCollection(targetType.getType(), (elementDescriptor != null) ? elementDescriptor.getType() : null, length); } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } } |
data class | Feature envy | t | f | f | Feature envy | data class | 0 | 4266 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DelimitedStringToCollectionConverter.java/#L37-L94 | 2 | 427 | 4266 | minor |
| 5391 | of the function below have bad smells NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 15152 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 5391 | 15152 | minor | ||
| 523 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | 'Long Method', 'Data Class' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',D,a,t,a," ",C,l,a,s,s,'} | {',o,n,g," ",M,t,h,o,d,',","," ",',D,t," ",C,'} | 0 | 5426 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 523 | 5426 | critical |
| 88 | { "answer": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1229 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 2 | 88 | 1229 | critical |
| 2270 | {"response": "YES I found bad smells\nthe bad smells are: \n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 13763 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 2270 | 13763 | minor |
| 2625 | { "response": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | long method | t | t | f | long method | data class | 0 | 15077 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 1 | 2625 | 15077 | minor |
| 714 | YES I found bad smells the bad smells are: 1. Long method 2. Large class 3. Data clumps 4. Duplicate code 5. Feature envy 6. Inappropriate intimacy 7. Primitive obsession 8. Refused bequest 9. Shotgun surgery 10. Speculative generality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class LazyIterate { private static final LazyIterable EMPTY_ITERABLE = Lists.immutable.empty().asLazy(); private LazyIterate() { throw new AssertionError("Suppress default constructor for noninstantiability"); } /** * Creates a deferred rich iterable for the specified iterable. */ public static LazyIterable adapt(Iterable iterable) { return new LazyIterableAdapter<>(iterable); } /** * Creates a deferred filtering iterable for the specified iterable. */ public static LazyIterable select(Iterable iterable, Predicate predicate) { return new SelectIterable<>(iterable, predicate); } /** * Creates a deferred negative filtering iterable for the specified iterable. */ public static LazyIterable reject(Iterable iterable, Predicate predicate) { return new RejectIterable<>(iterable, predicate); } public static LazyIterable selectInstancesOf(Iterable iterable, Class clazz) { return new SelectInstancesOfIterable<>(iterable, clazz); } /** * Creates a deferred transforming iterable for the specified iterable. */ public static LazyIterable collect( Iterable iterable, Function function) { return new CollectIterable<>(iterable, function); } /** * Creates a deferred flattening iterable for the specified iterable. */ public static LazyIterable flatCollect( Iterable iterable, Function> function) { return new FlatCollectIterable<>(iterable, function); } /** * Creates a deferred filtering and transforming iterable for the specified iterable. */ public static LazyIterable collectIf( Iterable iterable, Predicate predicate, Function function) { return LazyIterate.select(iterable, predicate).collect(function); } /** * Creates a deferred take iterable for the specified iterable using the specified count as the limit. */ public static LazyIterable take(Iterable iterable, int count) { return new TakeIterable<>(iterable, count); } /** * Creates a deferred drop iterable for the specified iterable using the specified count as the size to drop. */ public static LazyIterable drop(Iterable iterable, int count) { return new DropIterable<>(iterable, count); } /** * Creates a deferred takeWhile iterable for the specified iterable using the specified predicate. * Short circuits at the first element which does not satisfy the Predicate. * * @since 8.0 */ public static LazyIterable takeWhile(Iterable iterable, Predicate predicate) { return new TakeWhileIterable<>(iterable, predicate); } /** * Creates a deferred dropWhile iterable for the specified iterable using the specified count as the size to drop. * Short circuits at the first element which satisfies the Predicate. * * @since 8.0 */ public static LazyIterable dropWhile(Iterable iterable, Predicate predicate) { return new DropWhileIterable<>(iterable, predicate); } /** * Creates a deferred distinct iterable for the specified iterable. * * @since 5.0 */ public static LazyIterable distinct(Iterable iterable) { return new DistinctIterable<>(iterable); } /** * Combines iterables into a deferred composite iterable. */ public static LazyIterable concatenate(Iterable... iterables) { return CompositeIterable.with(iterables); } public static LazyIterable empty() { return (LazyIterable) EMPTY_ITERABLE; } public static LazyIterable> zip(Iterable as, Iterable bs) { return new ZipIterable<>(as, bs); } public static LazyIterable> zipWithIndex(Iterable iterable) { return new ZipWithIndexIterable<>(iterable); } public static LazyIterable> chunk(Iterable iterable, int size) { return new ChunkIterable<>(iterable, size); } /** * Creates a deferred tap iterable for the specified iterable. * * @since 6.0 */ public static LazyIterable tap(Iterable iterable, Procedure procedure) { return new TapIterable<>(iterable, procedure); } /** * Create a deferred cartesian product of the two specified iterables. * * See {@link LazyIterate#cartesianProduct(Iterable, Iterable, Function2)} about performance and presence of duplicates. * * @since 10.0 */ public static LazyIterable> cartesianProduct(Iterable iterable1, Iterable iterable2) { return LazyIterate.cartesianProduct(iterable1, iterable2, Tuples::pair); } /** * Create a deferred cartesian product of the two specified iterables. * * This operation has O(n^2) performance. * * The presence of duplicates in the resulting iterable is both dependent on the * presence of duplicates in the two specified iterables, and on the behaviour * of the terminating operation that is applied to the resulting lazy iterable. * * @since 10.0 */ public static LazyIterable cartesianProduct(Iterable iterable1, Iterable iterable2, Function2 function) { return LazyIterate.flatCollect(iterable1, first -> LazyIterate.collect(iterable2, second -> function.value(first, second))); } } |
blob | Long method 2 Large class 3 Data clumps 4 Duplicate code 5 Feature envy 6 Inappropriate intimacy 7 Primitive obsession 8 Refused bequest 9 Shotgun surgery | t | f | f | . Long method 2. Large class 3. Data clumps 4. Duplicate code 5. Feature envy 6. Inappropriate intimacy 7. Primitive obsession 8. Refused bequest 9. Shotgun surgery | blob | 0 | 6804 | https://github.com/eclipse/eclipse-collections/blob/fa40c9aadbd36fb08f05a60b200e92ace40a7bfd/eclipse-collections/src/main/java/org/eclipse/collections/impl/utility/LazyIterate.java/#L47-L229 | 2 | 714 | 6804 | minor |
| 2537 | {"response": "YES I found bad smells", "the bad smells are:": [ "Long method", "Long parameter list", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BrocadeVcsApi { private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class); private final String _host; private final String _adminuser; private final String _adminpass; protected DefaultHttpClient _client; protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { String url; try { url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Brocade Switch API URL", e); throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); } if ("post".equalsIgnoreCase(type)) { return new HttpPost(url); } else if ("get".equalsIgnoreCase(type)) { return new HttpGet(url); } else if ("delete".equalsIgnoreCase(type)) { return new HttpDelete(url); } else if ("patch".equalsIgnoreCase(type)) { return new HttpPatch(url); } else { throw new BrocadeVcsApiException("Requesting unknown method type"); } } public BrocadeVcsApi(String address, String username, String password) { _host = address; _adminuser = username; _adminpass = password; _client = new DefaultHttpClient(); _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); } /* * Get Operational Status */ public Output getSwitchStatus() throws BrocadeVcsApiException { return executeRetreiveStatus(Constants.STATUS_URI); } /* * Creates a new virtual network. */ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (createInterfaceVlan(vlanId)) { final PortProfile portProfile = createPortProfile(vlanId, networkId); if (portProfile != null) { return activatePortProfile(portProfile); } } return false; } /* * Activates a port-profile. */ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); portProfile.setVlanProfile(null); final Activate activate = new Activate(); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Creates AMPP port-profile. */ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); if (executeCreateObject(portProfile, Constants.URI)) { if (createVlanSubProfile(vlanId, portProfile)) { return portProfile; } } return null; } /* * Create vlan sub-profile for port-profile */ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final VlanProfile vlanProfile = new VlanProfile(); portProfile.setVlanProfile(vlanProfile); if (executeUpdateObject(portProfile, Constants.URI)) { return configureVlanSubProfile(vlanId, portProfile); } return false; } /* * Configures vlan sub-profile for port-profile. * - configure L2 mode for vlan sub-profile * - configure trunk mode for vlan sub-profile * - configure allowed VLANs for vlan sub-profile */ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final SwitchportBasic switchPortBasic = new SwitchportBasic(); final Basic basic = new Basic(); switchPortBasic.setBasic(basic); portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); // configure L2 mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { VlanProfile vlanProfile = new VlanProfile(); Switchport switchPort = new Switchport(); final Mode mode = new Mode(); mode.setVlanMode("trunk"); switchPort.setMode(mode); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); // configure trunk mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { vlanProfile = new VlanProfile(); switchPort = new Switchport(); final Trunk trunk = new Trunk(); final Allowed allowed = new Allowed(); final Allowed.Vlan allowedVlan = new Allowed.Vlan(); allowedVlan.setAdd(vlanId); allowed.setVlan(allowedVlan); trunk.setAllowed(allowed); switchPort.setTrunk(trunk); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); //configure allowed VLANs for vlan sub-profile return executeUpdateObject(portProfile, Constants.URI); } } return false; } /* * Creates a vlan interface. */ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Associates a MAC address to virtual network. */ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Disassociates a MAC address from virtual network. */ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setOperation("delete"); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes a new virtual network. */ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (deactivatePortProfile(networkId)) { if (deletePortProfile(networkId)) { return deleteInterfaceVlan(vlanId); } } return false; } /* * Deletes a vlan interface. */ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setOperation("delete"); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Deactivates a port-profile. */ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Activate activate = new Activate(); activate.setOperation("delete"); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes AMPP port-profile. */ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); portProfile.setOperation("delete"); //deletes port-profile return executeUpdateObject(portProfile, Constants.URI); } protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { final boolean result = true; if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpPatch pm = (HttpPatch)createMethod("patch", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to update object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); return result; } protected String convertToString(T object) throws BrocadeVcsApiException { final StringWriter stringWriter = new StringWriter(); try { final JAXBContext context = JAXBContext.newInstance(object.getClass()); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, stringWriter); } catch (final JAXBException e) { s_logger.error("Failed to convert object to string : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); } final String str = stringWriter.toString(); s_logger.info(str); return str; } protected Output convertToXML(String object) throws BrocadeVcsApiException { Output output = null; try { final JAXBContext context = JAXBContext.newInstance(Output.class); final StringReader reader = new StringReader(object); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(reader); if (result instanceof Output) { output = (Output)result; s_logger.info(output); } } catch (final JAXBException e) { s_logger.error("Failed to convert string to object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); } return output; } protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final boolean result = true; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to create object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return result; } protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while ((readLine = br.readLine()) != null) { s_logger.debug(readLine); sb.append(readLine); } } catch (final Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); } protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpDelete dm = (HttpDelete)createMethod("delete", uri); dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); final HttpResponse response = executeMethod(dm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to delete object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); } dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); } protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { HttpResponse response = null; try { response = _client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); response = _client.execute(method); } } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Brocade Switch", e); method.releaseConnection(); throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); } return response; } private String responseToErrorMessage(HttpResponse response) throws IOException { if ("text/html".equals(response.getEntity().getContentType().getValue())) { try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } } return null; } } |
blob | long method, long parameter list, feature envy | t | t | f | long method, long parameter list, feature envy | blob | 0 | 14767 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java/#L63-L542 | 2 | 2537 | 14767 | major |
| 1494 | YES I found bad smells the bad smells are: 1. Magic number (value -3096346807579L is not explained) 2. Public fields that should be private with getters/setters 3. Unused field serialVersionUID 4. Constructor with parameters that could be replaced with a default constructor and setters 5. Class name does not accurately describe its purpose or functionality 6. Lack of proper documentation/comments 7. No use of object-oriented concepts (e.g. encapsulation) 8. Serializable interface not implemented correctly or for no apparent reason. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | Magic number (value -3096346807579L is not explained)2 Public fields that should be private with getters/setters3 Unused field serialVersionUID 4 Constructor with parameters that could be replaced with a default constructor and setters 5 Class name does not accurately describe its purpose or functionality 6 Lack of proper documentation/comments 7 No use of object-oriented concepts (eg encapsulation) 8 Serializable interface not implemented correctly or for no apparent reason | t | f | f | . Magic number (value -3096346807579L is not explained)2. Public fields that should be private with getters/setters3. Unused field serialVersionUID 4. Constructor with parameters that could be replaced with a default constructor and setters 5. Class name does not accurately describe its purpose or functionality 6. Lack of proper documentation/comments 7. No use of object-oriented concepts (e.g. encapsulation) 8. Serializable interface not implemented correctly or for no apparent reason. | data class | 0 | 11123 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 2 | 1494 | 11123 | major |
| 1333 | YES I found bad smells the bad smells are: 1. Empty class 2. Unnecessary use of generics in ThreadLocal declaration | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CurrentCreationalContext { private final ThreadLocal> creationalContext = new ThreadLocal>(); public CreationalContext get() { return creationalContext.get(); } public void set(CreationalContext value) { creationalContext.set(value); } public void remove() { creationalContext.remove(); } } |
blob | Empty class2 Unnecessary use of generics in ThreadLocal declaration | t | f | f | . Empty class2. Unnecessary use of generics in ThreadLocal declaration | blob | 0 | 10719 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/cdi/CurrentCreationalContext.java/#L24-L38 | 2 | 1333 | 10719 | critical |
| 2706 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15347 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 2706 | 15347 | major |
| 1608 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XPathParser { private final Map prefixes = new HashMap(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // for compatibility return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11455 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/sax/xpath/XPathParser.java/#L40-L120 | 2 | 1608 | 11455 | minor |
| 1723 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11798 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 | 2 | 1723 | 11798 | critical |
| 1056 | YES, I found bad smells the bad smells are: 1. Feature envy: - The HttpsTokenInInterceptor class is responsible for handling messages and asserting policies related to HTTPS tokens, but it relies heavily on the PolicyUtils class, which can be considered a form of feature envy. 2. Long method: - The handleMessage() method contains a large amount of logic, with multiple nested if statements and try-catch blocks. This can make the code difficult to read and understand, and potentially lead to bugs. - The assertHttps() method is also quite long and contains a lot of duplicated code. 3. Primitive obsession: - In the assertHttps() method, there is heavy use of hardcoded string values, such as "Authorization" and "Basic", which could be replaced with constants for better readability and maintainability. 4. Temporary fields: - The assertHttps() method contains temporary fields such as the boolean asserted and the HttpsTokenSecurityEvent httpsTokenSecurityEvent, which are used to store intermediate values for later retrieval. This can indicate a need for refactoring and simplification of the code. 5. Long parameter list: - The assertHttps() method has 3 parameters, which can make the method difficult to understand and maintain, especially as more features are added. 6. Inappropriate use of comments: - There are multiple comments throughout the code, but they only state what the code is doing in plain language, which does not add any additional value and can make the code feel cluttered. 7. Dead code: - In the assertHttps() method, there is a block of code that checks for an "httpsTokenSecurityEvent" authentication type, but there is no logic or code that follows this check. 8. Inappropriate use of try-catch: - In the assertHttps() and assertNonHttpsTransportToken() methods, there are try-catch blocks that only log the exception and do not handle it in any way. This can lead to potential errors going unnoticed and makes the code less efficient. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class HttpsTokenInInterceptor extends AbstractPhaseInterceptor { HttpsTokenInInterceptor() { super(Phase.PRE_STREAM); addBefore(WSS4JStaxInInterceptor.class.getName()); } public void handleMessage(Message message) throws Fault { AssertionInfoMap aim = message.get(AssertionInfoMap.class); // extract Assertion information if (aim != null) { Collection ais = PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.HTTPS_TOKEN); boolean requestor = isRequestor(message); if (ais.isEmpty()) { if (!requestor) { try { assertNonHttpsTransportToken(message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } } return; } if (!requestor) { try { assertHttps(aim, ais, message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } // Store the TLS principal on the message context SecurityContext sc = message.get(SecurityContext.class); if (sc == null || sc.getUserPrincipal() == null) { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null && tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0 && (tlsInfo.getPeerCertificates()[0] instanceof X509Certificate) ) { X509Certificate cert = (X509Certificate)tlsInfo.getPeerCertificates()[0]; message.put( SecurityContext.class, createSecurityContext(cert.getSubjectX500Principal()) ); } } } else { //client side should be checked on the way out for (AssertionInfo ai : ais) { ai.setAsserted(true); } PolicyUtils.assertPolicy(aim, SPConstants.HTTP_DIGEST_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.HTTP_BASIC_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.REQUIRE_CLIENT_CERTIFICATE); } } } private void assertHttps( AssertionInfoMap aim, Collection ais, Message message ) throws XMLSecurityException { List securityEvents = getSecurityEventList(message); AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); for (AssertionInfo ai : ais) { boolean asserted = true; HttpsToken token = (HttpsToken)ai.getAssertion(); HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); Map> headers = getProtocolHeaders(message); if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpBasicAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Basic")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpBasicAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(true, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_BASIC_AUTHENTICATION)); } } if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpDigestAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Digest")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpDigestAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(false, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_DIGEST_AUTHENTICATION)); } } TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { if (token.getAuthenticationType() == HttpsToken.AuthenticationType.RequireClientCertificate) { if (tlsInfo.getPeerCertificates() == null || tlsInfo.getPeerCertificates().length == 0) { asserted = false; } else { PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.REQUIRE_CLIENT_CERTIFICATE)); } } if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } } else { asserted = false; } ai.setAsserted(asserted); if (asserted) { securityEvents.add(httpsTokenSecurityEvent); } } } // We might have an IssuedToken TransportToken private void assertNonHttpsTransportToken(Message message) throws XMLSecurityException { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } List securityEvents = getSecurityEventList(message); securityEvents.add(httpsTokenSecurityEvent); } } private List getSecurityEventList(Message message) { @SuppressWarnings("unchecked") List securityEvents = (List) message.getExchange().get(SecurityEvent.class.getName() + ".out"); if (securityEvents == null) { securityEvents = new ArrayList<>(); message.getExchange().put(SecurityEvent.class.getName() + ".out", securityEvents); } return securityEvents; } private SecurityContext createSecurityContext(final Principal p) { return new SecurityContext() { public Principal getUserPrincipal() { return p; } public boolean isUserInRole(String role) { return false; } }; } } |
blob | Feature envy:- The HttpsTokenInInterceptor class is responsible for handling messages and asserting policies related to HTTPS tokens, but it relies heavily on the PolicyUtils class, which can be considered a form of feature envy2 Long method:- The handleMessage() method contains a large amount of logic, with multiple nested if statements and try-catch blocks This can make the code difficult to read and understand, and potentially lead to bugs- The assertHttps() method is also quite long and contains a lot of duplicated code3 Primitive obsession:- In the assertHttps() method, there is heavy use of hardcoded string values, such as "Authorization" and "Basic", which could be replaced with constants for better readability and maintainability4 Temporary fields:- The assertHttps() method contains temporary fields such as the boolean asserted and the HttpsTokenSecurityEvent httpsTokenSecurityEvent, which are used to store intermediate values for later retrieval This can indicate a need for refactoring and simplification of the code5 Long parameter list:- The assertHttps() method has 3 parameters, which can make the method difficult to understand and maintain, especially as more features are added6 Inappropriate use of comments:- There are multiple comments throughout the code, but they only state what the code is doing in plain language, which does not add any additional value and can make the code feel cluttered7 Dead code:- In the assertHttps() method, there is a block of code that checks for an "httpsTokenSecurityEvent" authentication type, but there is no logic or code that follows this check8 Inappropriate use of try-catch:- In the assertHttps() and assertNonHttpsTransportToken() methods, there are try-catch blocks that only log the exception and do not handle it in any way This can lead to potential errors going unnoticed and makes the code less efficient | t | f | f | . Feature envy:- The HttpsTokenInInterceptor class is responsible for handling messages and asserting policies related to HTTPS tokens, but it relies heavily on the PolicyUtils class, which can be considered a form of feature envy.2. Long method:- The handleMessage() method contains a large amount of logic, with multiple nested if statements and try-catch blocks. This can make the code difficult to read and understand, and potentially lead to bugs.- The assertHttps() method is also quite long and contains a lot of duplicated code.3. Primitive obsession:- In the assertHttps() method, there is heavy use of hardcoded string values, such as "Authorization" and "Basic", which could be replaced with constants for better readability and maintainability.4. Temporary fields:- The assertHttps() method contains temporary fields such as the boolean asserted and the HttpsTokenSecurityEvent httpsTokenSecurityEvent, which are used to store intermediate values for later retrieval. This can indicate a need for refactoring and simplification of the code.5. Long parameter list:- The assertHttps() method has 3 parameters, which can make the method difficult to understand and maintain, especially as more features are added.6. Inappropriate use of comments:- There are multiple comments throughout the code, but they only state what the code is doing in plain language, which does not add any additional value and can make the code feel cluttered.7. Dead code:- In the assertHttps() method, there is a block of code that checks for an "httpsTokenSecurityEvent" authentication type, but there is no logic or code that follows this check.8. Inappropriate use of try-catch:- In the assertHttps() and assertNonHttpsTransportToken() methods, there are try-catch blocks that only log the exception and do not handle it in any way. This can lead to potential errors going unnoticed and makes the code less efficient. | blob | 0 | 9514 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/HttpsTokenInterceptorProvider.java/#L191-L390 | 2 | 1056 | 9514 | major |
| 1183 | { "output": "YES I found bad smells the bad smells are: 4. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | 4. long method | t | t | f | 4. long method | data class | 0 | 10238 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 1183 | 10238 | major |
| 377 | {"message": "YES I found bad smells", "bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class JsonObjects { private static final Jsonb JSON = JsonbBuilder.create(); private JsonObjects() { } static List getColumns(JsonObject jsonObject) { Map map = JSON.fromJson(jsonObject.toString(), Map.class); return Columns.of(map); } } |
data class | blob | t | t | f | blob | data class | 0 | 3896 | https://github.com/eclipse/jnosql/blob/9f03fa6ffe2dd4b538f7dbce424649aa4e484657/communication/diana-column/src/main/java/org/jnosql/diana/api/column/query/JsonObjects.java/#L28-L40 | 1 | 377 | 3896 | minor |
| 474 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean supportsParameter(MethodParameter parameter) { if (!super.supportsParameter(parameter)) { return false; } Class type = parameter.getParameterType(); if (!type.isInterface()) { return false; } // Annotated parameter if (parameter.getParameterAnnotation(ProjectedPayload.class) != null) { return true; } // Annotated type if (AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null) { return true; } // Fallback for only user defined interfaces String packageName = ClassUtils.getPackageName(type); return !IGNORED_PACKAGES.stream().anyMatch(it -> packageName.startsWith(it)); } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 4578 | https://github.com/spring-projects/spring-data-commons/blob/48c9297118e18273a0a3dfe3cf2f9a8ffd8fdca7/src/main/java/org/springframework/data/web/ProxyingHandlerMethodArgumentResolver.java/#L88-L115 | 2 | 474 | 4578 | minor |
| 735 | YES I found bad smells the bad smells are: 1. Unused parent class VersionedLabel 2. Using concrete class InstantiatedVersionedLabel instead of interface 3. Code duplication in constructor InstantiatedVersionedLabel() | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | Unused parent class VersionedLabel2 Using concrete class InstantiatedVersionedLabel instead of interface3 Code duplication in constructor InstantiatedVersionedLabel() | t | f | f | . Unused parent class VersionedLabel2. Using concrete class InstantiatedVersionedLabel instead of interface3. Code duplication in constructor InstantiatedVersionedLabel() | data class | 0 | 6908 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 735 | 6908 | minor |
| 2285 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | long method | t | t | f | long method | data class | 0 | 13867 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 2285 | 13867 | minor |
| 1558 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11299 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 2 | 1558 | 11299 | major |
| 100 | { "output": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: 1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | the bad smells are: 1. long method | t | t | f | the bad smells are: 1. long method | data class | 0 | 1304 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 1 | 100 | 1304 | minor |
| 2227 | YES I found bad smells the bad smells are: 1. Long method 2. Data Clumps | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Data Clumps | t | f | f | . Long method2. Data Clumps | data class | 0 | 13578 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 2227 | 13578 | minor |
| 60 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 1007 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 | 1 | 60 | 1007 | major |
| 899 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Deprecated methods 3. Feature envy - get and set methods for private member variables 4. Long method - multiple public methods with simple logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | Magic numbers2 Deprecated methods3 Feature envy - get and set methods for private member variables4 Long method - multiple public methods with simple logic | t | f | f | . Magic numbers2. Deprecated methods3. Feature envy - get and set methods for private member variables4. Long method - multiple public methods with simple logic | data class | 0 | 8152 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 2 | 899 | 8152 | critical |
| 5148 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14405 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 5148 | 14405 | minor |
| 2023 | "YES I found bad smells" the bad smells are: 1. Magic numbers 2. Hard-coded string literals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Magic numbers2 Hard-coded string literals | t | f | f | . Magic numbers2. Hard-coded string literals | feature envy | 0 | 12796 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 2023 | 12796 | major |
| 1166 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10184 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 1166 | 10184 | minor |
| 4062 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10721 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 | 2 | 4062 | 10721 | major |
| 690 | YES I found bad smells the bad smells are: 1. Long method (send) 2. Feature envy (ContainerDispatcher and TokenVerifier are used in multiple methods, could be extracted to their own classes) 3. Long parameter list (ContainerCommandRequestProto and ContainerCommandResponseProto are used as parameters) 4. Magic numbers (the boolean value false is used without explanation) 5. Hard-coded variables (LOG, LoggerFactory) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GrpcXceiverService extends XceiverClientProtocolServiceGrpc.XceiverClientProtocolServiceImplBase { public static final Logger LOG = LoggerFactory.getLogger(GrpcXceiverService.class); private final ContainerDispatcher dispatcher; private final boolean isGrpcTokenEnabled; private final TokenVerifier tokenVerifier; public GrpcXceiverService(ContainerDispatcher dispatcher) { this(dispatcher, false, null); } public GrpcXceiverService(ContainerDispatcher dispatcher, boolean grpcTokenEnabled, TokenVerifier tokenVerifier) { this.dispatcher = dispatcher; this.isGrpcTokenEnabled = grpcTokenEnabled; this.tokenVerifier = tokenVerifier; } @Override public StreamObserver send( StreamObserver responseObserver) { return new StreamObserver() { private final AtomicBoolean isClosed = new AtomicBoolean(false); @Override public void onNext(ContainerCommandRequestProto request) { try { if(isGrpcTokenEnabled) { // ServerInterceptors intercepts incoming request and creates ugi. tokenVerifier.verify(UserGroupInformation.getCurrentUser() .getShortUserName(), request.getEncodedToken()); } ContainerCommandResponseProto resp = dispatcher.dispatch(request, null); responseObserver.onNext(resp); } catch (Throwable e) { LOG.error("{} got exception when processing" + " ContainerCommandRequestProto {}: {}", request, e); responseObserver.onError(e); } } @Override public void onError(Throwable t) { // for now we just log a msg LOG.error("{}: ContainerCommand send on error. Exception: {}", t); } @Override public void onCompleted() { if (isClosed.compareAndSet(false, true)) { LOG.debug("{}: ContainerCommand send completed"); responseObserver.onCompleted(); } } }; } } |
blob | Long method (send)2 Feature envy (ContainerDispatcher and TokenVerifier are used in multiple methods, could be extracted to their own classes)3 Long parameter list (ContainerCommandRequestProto and ContainerCommandResponseProto are used as parameters)4 Magic numbers (the boolean value false is used without explanation)5 Hard-coded variables (LOG, LoggerFactory) | t | f | f | . Long method (send)2. Feature envy (ContainerDispatcher and TokenVerifier are used in multiple methods, could be extracted to their own classes)3. Long parameter list (ContainerCommandRequestProto and ContainerCommandResponseProto are used as parameters)4. Magic numbers (the boolean value false is used without explanation)5. Hard-coded variables (LOG, LoggerFactory) | blob | 0 | 6650 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/transport/server/GrpcXceiverService.java/#L38-L97 | 2 | 690 | 6650 | minor |
| 262 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | feature envy, long method | t | t | f | feature envy, long method | data class | 0 | 2850 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 262 | 2850 | critical |
| 485 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 4746 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 | 1 | 485 | 4746 | minor |
| 8 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 592 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 2 | 8 | 592 | major |
| 1729 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 11813 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 2 | 1729 | 11813 | major |
| 1275 | { "output": "YES I found bad smells\nthe bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | long method | t | t | f | long method | blob | 0 | 10583 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 1 | 1275 | 10583 | minor |
| 2672 | YES I found bad smells The bad smells are: 1. Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability). 2. Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability)2 Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion) | t | f | f | . Long methods (methods that could potentially be broken down into smaller, more specific methods for increased readability and maintainability).2. Feature envy (methods that access and manipulate data from other classes, indicating a potential lack of encapsulation and cohesion). | data class | 0 | 15216 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 2 | 2672 | 15216 | minor |
| 2609 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15033 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 2 | 2609 | 15033 | minor |
| 2113 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | long method | t | t | f | long method | data class | 0 | 13191 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 1 | 2113 | 13191 | minor |
| 4008 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10594 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 4008 | 10594 | major |
| 1014 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 9295 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 1014 | 9295 | minor |
| 1059 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 9530 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 2 | 1059 | 9530 | minor |
| 1953 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12539 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 1 | 1953 | 12539 | critical |
| 2631 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 15100 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 2 | 2631 | 15100 | major |
| 677 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 6583 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 1 | 677 | 6583 | minor |
| 2353 | are found NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14224 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2353 | 14224 | minor | ||
| 2308 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14094 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 2 | 2308 | 14094 | major |
| 4726 | {"NO, I did not find any bad smell" : " "} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DiscoverAnnotatedBeans implements DynamicDeployer { public AppModule deploy(AppModule appModule) throws OpenEJBException { for (EjbModule ejbModule : appModule.getEjbModules()) { ejbModule.initAppModule(appModule); setModule(ejbModule); try { deploy(ejbModule); } finally { removeModule(); } } for (ClientModule clientModule : appModule.getClientModules()) { clientModule.initAppModule(appModule); setModule(clientModule); try { deploy(clientModule); } finally { removeModule(); } } for (ConnectorModule connectorModule : appModule.getConnectorModules()) { connectorModule.initAppModule(appModule); setModule(connectorModule); try { deploy(connectorModule); } finally { removeModule(); } } for (WebModule webModule : appModule.getWebModules()) { webModule.initAppModule(appModule); setModule(webModule); try { deploy(webModule); } finally { removeModule(); } } final AdditionalBeanDiscoverer discoverer = SystemInstance.get().getComponent(AdditionalBeanDiscoverer.class); if (discoverer != null) { appModule = discoverer.discover(appModule); } return appModule; } public ClientModule deploy(ClientModule clientModule) throws OpenEJBException { if (clientModule.getApplicationClient() == null){ clientModule.setApplicationClient(new ApplicationClient()); } // Lots of jars have main classes so this might not even be an app client. // We're not going to scrape it for @LocalClient or @RemoteClient annotations // unless they flag us specifically by adding a META-INF/application-client.xml // // ClientModules that already have a AnnotationFinder have been generated automatically // from an EjbModule, so we don't skip those ever. if (clientModule.getFinder() == null && clientModule.getAltDDs().containsKey("application-client.xml")) if (clientModule.getApplicationClient() != null && clientModule.getApplicationClient().isMetadataComplete()) return clientModule; IAnnotationFinder finder = clientModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(clientModule); } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForClientModule.url", clientModule.getJarLocation()); return clientModule; } catch (Exception e) { startupLogger.warning("startup.scrapeFailedForClientModule", e, clientModule.getJarLocation()); return clientModule; } } // This method is also called by the deploy(EjbModule) method to see if those // modules have any @LocalClient or @RemoteClient classes for (Annotated> clazz : finder.findMetaAnnotatedClasses(LocalClient.class)) { clientModule.getLocalClients().add(clazz.get().getName()); } for (Annotated> clazz : finder.findMetaAnnotatedClasses(RemoteClient.class)) { clientModule.getRemoteClients().add(clazz.get().getName()); } if (clientModule.getApplicationClient() == null){ if (clientModule.getRemoteClients().size() > 0 || clientModule.getLocalClients().size() > 0) { clientModule.setApplicationClient(new ApplicationClient()); } } return clientModule; } public ConnectorModule deploy(ConnectorModule connectorModule) throws OpenEJBException { org.apache.openejb.jee.Connector connector = connectorModule.getConnector(); if (connector == null) { connector = new org.apache.openejb.jee.Connector(); } // JCA 1.6 - 18.3.1 do not look at annotations if the provided connector // deployment descriptor is "meta-data complete". float specVersion = 0; try { specVersion = Float.parseFloat(connector.getVersion()); } catch (Exception e) { } if (specVersion < 1.6 || Boolean.TRUE.equals(connector.isMetadataComplete())) { return connectorModule; } IAnnotationFinder finder = connectorModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(connectorModule); connectorModule.setFinder(finder); } catch (Exception e) { // TODO: some sort of error return connectorModule; } } List> connectorClasses = finder.findAnnotatedClasses(Connector.class); // are we allowed to have more than one connector class? Not without a deployment descriptor if (connector.getResourceAdapter() == null || connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { if (connectorClasses.size() == 0) { // fail some validation here too } if (connectorClasses.size() > 1) { // too many connector classes, this is against the spec // something like connectorModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); } } Class connectorClass = null; if (connectorClasses.size() == 1) { connectorClass = connectorClasses.get(0); } if (connectorClasses.size() > 1) { for (Class cls : connectorClasses) { if (cls.getName().equals(connector.getResourceAdapter().getResourceAdapterClass())) { connectorClass = cls; break; } } } if (connectorClass != null) { if (connector.getResourceAdapter() == null) { connector.setResourceAdapter(new ResourceAdapter()); } if (connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { connector.getResourceAdapter().setResourceAdapterClass(connectorClass.getName()); } Connector connectorAnnotation = connectorClass.getAnnotation(Connector.class); connector.setDisplayNames(getTexts(connector.getDisplayNames(), connectorAnnotation.displayName())); connector.setDescriptions(getTexts(connector.getDescriptions(), connectorAnnotation.description())); connector.setEisType(getString(connector.getEisType(), connectorAnnotation.eisType())); connector.setVendorName(getString(connector.getVendorName(), connectorAnnotation.vendorName())); connector.setResourceAdapterVersion(getString(connector.getResourceAdapterVersion(), connectorAnnotation.version())); if (connector.getIcons().isEmpty()) { int smallIcons = connectorAnnotation.smallIcon().length; int largeIcons = connectorAnnotation.largeIcon().length; for (int i = 0; i < smallIcons && i < largeIcons; i++) { Icon icon = new Icon(); // locale can't be specified in the annotation and it is en by default // so on other systems it doesn't work because Icon return the default locale icon.setLang(Locale.getDefault().getLanguage()); if (i < smallIcons) { icon.setSmallIcon(connectorAnnotation.smallIcon()[i]); } if (i < largeIcons) { icon.setLargeIcon(connectorAnnotation.largeIcon()[i]); } connector.getIcons().add(icon); } } if (connector.getLicense() == null) { License license = new License(); connector.setLicense(license); license.setLicenseRequired(connectorAnnotation.licenseRequired()); } connector.getLicense().setDescriptions(getTexts(connector.getLicense().getDescriptions(), connectorAnnotation.licenseDescription())); SecurityPermission[] annotationSecurityPermissions = connectorAnnotation.securityPermissions(); List securityPermission = connector.getResourceAdapter().getSecurityPermission(); if (securityPermission == null || securityPermission.size() == 0) { for (SecurityPermission sp : annotationSecurityPermissions) { org.apache.openejb.jee.SecurityPermission permission = new org.apache.openejb.jee.SecurityPermission(); permission.setSecurityPermissionSpec(sp.permissionSpec()); permission.setDescriptions(stringsToTexts(sp.description())); securityPermission.add(permission); } } Class[] annotationRequiredWorkContexts = connectorAnnotation.requiredWorkContexts(); List requiredWorkContext = connector.getRequiredWorkContext(); if (requiredWorkContext.size() == 0) { for (Class cls : annotationRequiredWorkContexts) { requiredWorkContext.add(cls.getName()); } } OutboundResourceAdapter outboundResourceAdapter = connector.getResourceAdapter().getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); connector.getResourceAdapter().setOutboundResourceAdapter(outboundResourceAdapter); } List authenticationMechanisms = outboundResourceAdapter.getAuthenticationMechanism(); javax.resource.spi.AuthenticationMechanism[] authMechanisms = connectorAnnotation.authMechanisms(); if (authenticationMechanisms.size() == 0) { for (javax.resource.spi.AuthenticationMechanism am : authMechanisms) { AuthenticationMechanism authMechanism = new AuthenticationMechanism(); authMechanism.setAuthenticationMechanismType(am.authMechanism()); authMechanism.setCredentialInterface(am.credentialInterface().toString()); authMechanism.setDescriptions(stringsToTexts(am.description())); authenticationMechanisms.add(authMechanism); } } if (outboundResourceAdapter.getTransactionSupport() == null) { outboundResourceAdapter.setTransactionSupport(TransactionSupportType.fromValue(connectorAnnotation.transactionSupport().toString())); } if (outboundResourceAdapter.isReauthenticationSupport() == null) { outboundResourceAdapter.setReauthenticationSupport(connectorAnnotation.reauthenticationSupport()); } } else { // we couldn't process a connector class - probably a validation issue which we should warn about. } // process @ConnectionDescription(s) List> classes = finder.findAnnotatedClasses(ConnectionDefinitions.class); for (Class cls : classes) { ConnectionDefinitions connectionDefinitionsAnnotation = cls.getAnnotation(ConnectionDefinitions.class); ConnectionDefinition[] definitions = connectionDefinitionsAnnotation.value(); for (ConnectionDefinition definition : definitions) { processConnectionDescription(connector.getResourceAdapter(), definition, cls); } } classes = finder.findAnnotatedClasses(ConnectionDefinition.class); for (Class cls : classes) { ConnectionDefinition connectionDefinitionAnnotation = cls.getAnnotation(ConnectionDefinition.class); processConnectionDescription(connector.getResourceAdapter(), connectionDefinitionAnnotation, cls); } InboundResourceadapter inboundResourceAdapter = connector.getResourceAdapter().getInboundResourceAdapter(); if (inboundResourceAdapter == null) { inboundResourceAdapter = new InboundResourceadapter(); connector.getResourceAdapter().setInboundResourceAdapter(inboundResourceAdapter); } MessageAdapter messageAdapter = inboundResourceAdapter.getMessageAdapter(); if (messageAdapter == null) { messageAdapter = new MessageAdapter(); inboundResourceAdapter.setMessageAdapter(messageAdapter); } classes = finder.findAnnotatedClasses(Activation.class); for (Class cls : classes) { MessageListener messageListener = null; Activation activationAnnotation = cls.getAnnotation(Activation.class); List messageListeners = messageAdapter.getMessageListener(); for (MessageListener ml : messageListeners) { if (cls.getName().equals(ml.getActivationSpec().getActivationSpecClass())) { messageListener = ml; break; } } if (messageListener == null) { Class[] listeners = activationAnnotation.messageListeners(); for (Class listener : listeners) { messageAdapter.addMessageListener(new MessageListener(listener.getName(), cls.getName())); } } } classes = finder.findAnnotatedClasses(AdministeredObject.class); List adminObjects = connector.getResourceAdapter().getAdminObject(); for (Class cls : classes) { AdministeredObject administeredObjectAnnotation = cls.getAnnotation(AdministeredObject.class); Class[] adminObjectInterfaces = administeredObjectAnnotation.adminObjectInterfaces(); AdminObject adminObject = null; for (AdminObject admObj : adminObjects) { if (admObj.getAdminObjectClass().equals(cls.getName())) { adminObject = admObj; } } if (adminObject == null) { for (Class iface : adminObjectInterfaces) { AdminObject newAdminObject = new AdminObject(); newAdminObject.setAdminObjectClass(cls.getName()); newAdminObject.setAdminObjectInterface(iface.getName()); adminObjects.add(newAdminObject); } } } // need to make a list of classes to process for config properties // resource adapter String raCls = connector.getResourceAdapter().getResourceAdapterClass(); process(connectorModule.getClassLoader(), raCls, connector.getResourceAdapter()); // managedconnectionfactory if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getOutboundResourceAdapter() != null) { List connectionDefinitions = connector.getResourceAdapter().getOutboundResourceAdapter().getConnectionDefinition(); for (org.apache.openejb.jee.ConnectionDefinition connectionDefinition : connectionDefinitions) { process(connectorModule.getClassLoader(), connectionDefinition.getManagedConnectionFactoryClass(), connectionDefinition); } } // administeredobject if (connector.getResourceAdapter() != null) { List raAdminObjects = connector.getResourceAdapter().getAdminObject(); for (AdminObject raAdminObject : raAdminObjects) { process(connectorModule.getClassLoader(), raAdminObject.getAdminObjectClass(), raAdminObject); } } // activationspec if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter() != null) { List messageListeners = connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter().getMessageListener(); for (MessageListener messageListener : messageListeners) { ActivationSpec activationSpec = messageListener.getActivationSpec(); process(connectorModule.getClassLoader(), activationSpec.getActivationSpecClass(), activationSpec); } } return connectorModule; } void process(ClassLoader cl, String cls, Object object) { List configProperties = null; try { // grab a list of ConfigProperty objects configProperties = (List) object.getClass().getDeclaredMethod("getConfigProperty").invoke(object); } catch (Exception e) { } if (configProperties == null) { // can't get config properties return; } ClassLoader classLoader = cl; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final List allowedTypes = Arrays.asList(new String[] { Boolean.class.getName(), String.class.getName(), Integer.class.getName(), Double.class.getName(), Byte.class.getName(), Short.class.getName(), Long.class.getName(), Float.class.getName(), Character.class.getName()}); try { Class clazz = classLoader.loadClass(realClassName(cls)); Object o = clazz.newInstance(); // add any introspected properties BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); Class type = propertyDescriptor.getPropertyType(); if (type == null) { continue; } if (type.isPrimitive()) { type = getWrapper(type.getName()); } if (! allowedTypes.contains(type.getName())) { continue; } if (! containsConfigProperty(configProperties, name)) { if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); Object value = null; try { value = propertyDescriptor.getReadMethod().invoke(o); } catch (Exception e) { } javax.resource.spi.ConfigProperty annotation = propertyDescriptor.getWriteMethod().getAnnotation(javax.resource.spi.ConfigProperty.class); if (annotation == null) { try { // if there's no annotation on the setter, we'll try and scrape one off the field itself (assuming the same name) annotation = clazz.getDeclaredField(name).getAnnotation(javax.resource.spi.ConfigProperty.class); } catch (Exception ignored) { // no-op : getDeclaredField() throws exceptions and does not return null } } configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(getConfigPropertyType(annotation, type)); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null && annotation.defaultValue().length() > 0) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); configProperty.setDescriptions(stringsToTexts(annotation.description())); } } } } // add any annotated fields we haven't already picked up Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { javax.resource.spi.ConfigProperty annotation = field.getAnnotation(javax.resource.spi.ConfigProperty.class); String name = field.getName(); Object value = null; try { value = field.get(o); } catch (Exception e) { } if (! containsConfigProperty(configProperties, name)) { String type = getConfigPropertyType(annotation, field.getType()); if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(type); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); } } } } } catch (Exception e) { e.printStackTrace(); } } private String getConfigPropertyType(javax.resource.spi.ConfigProperty annotation, Class type) { Class t = (annotation == null) ? null : annotation.type(); if (t == null && type != null) { return type.getName(); } else if (t == null) { return null; } if (t.equals(Object.class)) { t = type; } if (t == null) { // t == null && type == null return null; } if (t.isPrimitive()) { t = getWrapper(t.getName()); } return t.getName(); } private boolean containsConfigProperty(List configProperties, String name) { for (ConfigProperty configProperty : configProperties) { if (configProperty.getConfigPropertyName().equals(name)) { return true; } } return false; } private Class getWrapper(String primitiveType) { final Map> builtInMap = new HashMap>();{ builtInMap.put("int", Integer.class); builtInMap.put("long", Long.class); builtInMap.put("double", Double.class); builtInMap.put("float", Float.class); builtInMap.put("boolean", Boolean.class); builtInMap.put("char", Character.class); builtInMap.put("byte", Byte.class); builtInMap.put("void", Void.class); builtInMap.put("short", Short.class); } return builtInMap.get(primitiveType); } private void processConnectionDescription(ResourceAdapter resourceAdapter, ConnectionDefinition connectionDefinitionAnnotation, Class cls) { // try and find the managed connection factory OutboundResourceAdapter outboundResourceAdapter = resourceAdapter.getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); resourceAdapter.setOutboundResourceAdapter(outboundResourceAdapter); } List connectionDefinition = outboundResourceAdapter.getConnectionDefinition(); org.apache.openejb.jee.ConnectionDefinition definition = null; for (org.apache.openejb.jee.ConnectionDefinition cd : connectionDefinition) { if (cd.getManagedConnectionFactoryClass().equals(cls.getName())) { definition = cd; break; } } if (definition == null) { definition = new org.apache.openejb.jee.ConnectionDefinition(); outboundResourceAdapter.getConnectionDefinition().add(definition); } if (definition.getManagedConnectionFactoryClass() == null) { definition.setManagedConnectionFactoryClass(cls.getName()); } if (definition.getConnectionInterface() == null) { definition.setConnectionInterface(connectionDefinitionAnnotation.connection().getName()); } if (definition.getConnectionImplClass() == null) { definition.setConnectionImplClass(connectionDefinitionAnnotation.connectionImpl().getName()); } if (definition.getConnectionFactoryInterface() == null) { definition.setConnectionFactoryInterface(connectionDefinitionAnnotation.connectionFactory().getName()); } if (definition.getConnectionFactoryImplClass() == null) { definition.setConnectionFactoryImplClass(connectionDefinitionAnnotation.connectionFactoryImpl().getName()); } } private Text[] stringsToTexts(String[] strings) { if (strings == null) { return null; } Text[] result = new Text[strings.length]; for (int i = 0; i < result.length; i++) { result[i] = new Text(); result[i].setValue(strings[i]); } return result; } private String getString(String descriptorString, String annotationString) { if (descriptorString != null && descriptorString.length() > 0) { return descriptorString; } if (annotationString != null && annotationString.length() > 0) { return annotationString; } return null; } private Text[] getTexts(Text[] originalTexts, String[] newStrings) { if (newStrings != null && newStrings.length > 0 && (originalTexts == null || originalTexts.length == 0)) { Text[] texts = new Text[newStrings.length]; for (int i = 0; i < newStrings.length; i++) { texts[i] = new Text(null, newStrings[i]); } return texts; } else { return originalTexts; } } public WebModule deploy(WebModule webModule) throws OpenEJBException { WebApp webApp = webModule.getWebApp(); if (webApp != null && (webApp.isMetadataComplete())) return webModule; try { if (webModule.getFinder() == null) { webModule.setFinder(FinderFactory.createFinder(webModule)); } } catch (Exception e) { startupLogger.warning("Unable to scrape for @WebService or @WebServiceProvider annotations. AnnotationFinder failed.", e); return webModule; } if (webApp == null) { webApp = new WebApp(); webModule.setWebApp(webApp); } List existingServlets = new ArrayList(); for (Servlet servlet : webApp.getServlet()) { if (servlet.getServletClass() != null) { existingServlets.add(servlet.getServletClass()); } } IAnnotationFinder finder = webModule.getFinder(); List classes = new ArrayList(); classes.addAll(finder.findAnnotatedClasses(WebService.class)); classes.addAll(finder.findAnnotatedClasses(WebServiceProvider.class)); for (Class webServiceClass : classes) { // If this class is also annotated @Stateless or @Singleton, we should skip it if (webServiceClass.isAnnotationPresent(Singleton.class) || webServiceClass.isAnnotationPresent(Stateless.class)) { webModule.getEjbWebServices().add(webServiceClass.getName()); continue; } int modifiers = webServiceClass.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || isAbstract(modifiers)) { continue; } if (existingServlets.contains(webServiceClass.getName())) continue; // create webApp and webservices objects if they don't exist already // add new element Servlet servlet = new Servlet(); servlet.setServletName(webServiceClass.getName()); servlet.setServletClass(webServiceClass.getName()); webApp.getServlet().add(servlet); } /* * REST */ // get by annotations webModule.getRestClasses().addAll(findRestClasses(webModule, finder)); addJaxRsProviders(finder, webModule.getJaxrsProviders(), Provider.class); // Applications with a default constructor // findSubclasses will not work by default to gain a lot of time // look FinderFactory for the flag to activate it or // use @ApplicationPath("/") List> applications = finder.findSubclasses(Application.class); for (Class app : applications) { addRestApplicationIfPossible(webModule, app); } // look for ApplicationPath, it will often return the same than the previous one // but without finder.link() invocation it still works // so it can save a lot of startup time List>> applicationsByAnnotation = finder.findMetaAnnotatedClasses(ApplicationPath.class); for (Annotated> annotatedApp : applicationsByAnnotation) { final Class app = annotatedApp.get(); if (!Application.class.isAssignableFrom(app)) { logger.error("class '" + app.getName() + "' is annotated with @ApplicationPath but doesn't implement " + Application.class.getName()); continue; } addRestApplicationIfPossible(webModule, (Class) app); } /* * JSF */ final ClassLoader classLoader = webModule.getClassLoader(); for (String jsfClass : JSF_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(jsfClass); } catch (ClassNotFoundException e) { continue; } final List>> found = finder.findMetaAnnotatedClasses(clazz); final Set convertedClasses = new HashSet(found.size()); for (Annotated> annotated : found) { convertedClasses.add(annotated.get().getName()); } webModule.getJsfAnnotatedClasses().put(jsfClass, convertedClasses); } /* * Servlet, Filter, Listener */ Map urlByClasses = null; for (String apiClassName : WEB_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(apiClassName); } catch (ClassNotFoundException e) { continue; } if (urlByClasses == null) { // try to reuse scanning info, maybe some better indexing can be a nice idea if (finder instanceof FinderFactory.ModuleLimitedFinder) { final IAnnotationFinder limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (limitedFinder instanceof AnnotationFinder) { final Archive archive = ((AnnotationFinder) limitedFinder).getArchive(); if (archive instanceof WebappAggregatedArchive) { final Map> index = ((WebappAggregatedArchive) archive).getClassesMap(); urlByClasses = new HashMap(); for (Map.Entry> entry : index.entrySet()) { final String url = entry.getKey().toExternalForm(); for (String current : entry.getValue()) { urlByClasses.put(current, url); } } } } } } final List>> found = finder.findMetaAnnotatedClasses(clazz); addWebAnnotatedClassInfo(urlByClasses, webModule.getWebAnnotatedClasses(), found); } if (urlByClasses != null) { urlByClasses.clear(); } return webModule; } private void addJaxRsProviders(final IAnnotationFinder finder, final Collection set, final Class annotation) { for (Annotated> provider : finder.findMetaAnnotatedClasses(annotation)) { set.add(provider.get().getName()); } } private static void addRestApplicationIfPossible(final WebModule webModule, final Class app) { if (app.getConstructors().length == 0) { webModule.getRestApplications().add(app.getName()); } else { for (Constructor ctr : app.getConstructors()) { if (ctr.getParameterTypes().length == 0) { webModule.getRestApplications().add(app.getName()); break; } } } } public EjbModule deploy(EjbModule ejbModule) throws OpenEJBException { if (ejbModule.getEjbJar() != null && ejbModule.getEjbJar().isMetadataComplete()) return ejbModule; try { if (ejbModule.getFinder() == null) { ejbModule.setFinder(FinderFactory.createFinder(ejbModule)); } } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForModule", ejbModule.getJarLocation()); return ejbModule; } catch (Exception e) { startupLogger.warning("Unable to scrape for @Stateful, @Stateless, @Singleton or @MessageDriven annotations. AnnotationFinder failed.", e); return ejbModule; } IAnnotationFinder finder = ejbModule.getFinder(); final List managedClasses; { final Beans beans = ejbModule.getBeans(); if (beans != null) { managedClasses = beans.getManagedClasses(); final List classNames = getBeanClasses(finder); for (String rawClassName : classNames) { final String className = realClassName(rawClassName); try { final ClassLoader loader = ejbModule.getClassLoader(); final Class clazz = loader.loadClass(className); // The following can NOT be beans in CDI // 1. Non-static inner classes if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) continue; // // // 2. Abstract classes (unless they are an @Decorator) // if (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isAnnotationPresent(javax.decorator.Decorator.class)) continue; // // 3. Implementations of Extension if (Extension.class.isAssignableFrom(clazz)) continue; managedClasses.add(className); } catch (ClassNotFoundException e) { // todo log debug warning } catch (java.lang.NoClassDefFoundError e) { // no-op } } // passing jar location to be able to manage maven classes/test-classes which have the same moduleId String id = ejbModule.getModuleId(); if (ejbModule.getJarLocation() != null && ejbModule.getJarLocation().contains(ejbModule.getModuleId() + "/target/test-classes".replace("/", File.separator))) { // with maven if both src/main/java and src/test/java are deployed // moduleId.Comp exists twice so it fails // here we simply modify the test comp bean name to avoid it id += "_test"; } final String name = BeanContext.Comp.openejbCompName(id); final org.apache.openejb.jee.ManagedBean managedBean = new CompManagedBean(name, BeanContext.Comp.class); managedBean.setTransactionType(TransactionType.BEAN); ejbModule.getEjbJar().addEnterpriseBean(managedBean); } else { managedClasses = new ArrayList(); } } final Set> specializingClasses = new HashSet>(); // Fill in default sessionType for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (!(bean instanceof SessionBean)) continue; SessionBean sessionBean = (SessionBean) bean; if (sessionBean.getSessionType() != null) continue; try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); sessionBean.setSessionType(getSessionType(clazz)); } catch (Throwable handledInValidation) { // no-op } } // Fill in default ejbName for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (bean.getEjbClass() == null) continue; if (bean.getEjbName() == null || bean.getEjbName().startsWith("@NULL@")) { ejbModule.getEjbJar().removeEnterpriseBean(bean.getEjbName()); try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); final String ejbName = getEjbName(bean, clazz); bean.setEjbName(ejbName); } catch (Throwable handledInValidation) { } ejbModule.getEjbJar().addEnterpriseBean(bean); } } /* 19.2: ejb-name: Default is the unqualified name of the bean class */ EjbJar ejbJar = ejbModule.getEjbJar(); for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Singleton.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Singleton singleton = beanClass.getAnnotation(Singleton.class); String ejbName = getEjbName(singleton, beanClass.get()); if (!isValidEjbAnnotationUsage(Singleton.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new SingletonBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.SINGLETON); if (singleton.mappedName() != null) { sessionBean.setMappedName(singleton.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateless.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateless stateless = beanClass.getAnnotation(Stateless.class); String ejbName = getEjbName(stateless, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateless.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatelessBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.STATELESS); if (stateless.mappedName() != null) { sessionBean.setMappedName(stateless.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } // The Specialization code is good, but it possibly needs to be moved to after the full processing of the bean // the plus is that it would get the required interfaces. The minus is that it would get all the other items // Possibly study alternatives. Alternatives might have different meta data completely while it seems Specializing beans inherit all meta-data // Anyway.. the qualifiers aren't getting inherited, so we need to fix that for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateful.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateful stateful = beanClass.getAnnotation(Stateful.class); String ejbName = getEjbName(stateful, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateful.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatefulBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; // TODO: We might be stepping on an xml override here sessionBean.setSessionType(SessionType.STATEFUL); if (stateful.mappedName() != null) { sessionBean.setMappedName(stateful.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(ManagedBean.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } ManagedBean managed = beanClass.getAnnotation(ManagedBean.class); String ejbName = getEjbName(managed, beanClass.get()); // TODO: this is actually against the spec, but the requirement is rather silly // (allowing @Stateful and @ManagedBean on the same class) // If the TCK doesn't complain we should discourage it if (!isValidEjbAnnotationUsage(ManagedBean.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new org.apache.openejb.jee.ManagedBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.MANAGED); final TransactionType transactionType = sessionBean.getTransactionType(); if (transactionType == null) sessionBean.setTransactionType(TransactionType.BEAN); } } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(MessageDriven.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } MessageDriven mdb = beanClass.getAnnotation(MessageDriven.class); String ejbName = getEjbName(mdb, beanClass.get()); if (!isValidEjbAnnotationUsage(MessageDriven.class, beanClass, ejbName, ejbModule)) continue; MessageDrivenBean messageBean = (MessageDrivenBean) ejbJar.getEnterpriseBean(ejbName); if (messageBean == null) { messageBean = new MessageDrivenBean(ejbName); ejbJar.addEnterpriseBean(messageBean); } if (messageBean.getEjbClass() == null) { messageBean.setEjbClass(beanClass.get()); } LegacyProcessor.process(beanClass.get(), messageBean); } for (Class specializingClass : sortClassesParentFirst(new ArrayList>(specializingClasses))) { final Class parent = specializingClass.getSuperclass(); if (parent == null || parent.equals(Object.class)) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsNothing", specializingClass.getName()); } boolean found = false; for (EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) { final String ejbClass = enterpriseBean.getEjbClass(); if (ejbClass != null && ejbClass.equals(parent.getName())) { managedClasses.remove(ejbClass); enterpriseBean.setEjbClass(specializingClass.getName()); found = true; } } if (!found) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsSimpleBean", specializingClass.getName()); } } AssemblyDescriptor assemblyDescriptor = ejbModule.getEjbJar().getAssemblyDescriptor(); if (assemblyDescriptor == null) { assemblyDescriptor = new AssemblyDescriptor(); ejbModule.getEjbJar().setAssemblyDescriptor(assemblyDescriptor); } startupLogger.debug("Searching for annotated application exceptions (see OPENEJB-980)"); List> appExceptions = finder.findAnnotatedClasses(ApplicationException.class); for (Class exceptionClass : appExceptions) { startupLogger.debug("...handling " + exceptionClass); ApplicationException annotation = exceptionClass.getAnnotation(ApplicationException.class); if (assemblyDescriptor.getApplicationException(exceptionClass) == null) { startupLogger.debug("...adding " + exceptionClass + " with rollback=" + annotation.rollback()); assemblyDescriptor.addApplicationException(exceptionClass, annotation.rollback(), annotation.inherited()); } else { mergeApplicationExceptionAnnotation(assemblyDescriptor, exceptionClass, annotation); } } // ejb can be rest bean and only then in standalone so scan providers here too // adding them to app since they should be in the app classloader if (ejbModule.getAppModule() != null) { addJaxRsProviders(finder, ejbModule.getAppModule().getJaxRsProviders(), Provider.class); } if (ejbModule.getAppModule() != null) { for (PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) { for (org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) { if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses()) && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) { final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE); // no need of meta currently since JPA providers doesn't support it final List> classes = new ArrayList>(); classes.addAll(finder.findAnnotatedClasses(Entity.class)); classes.addAll(finder.findAnnotatedClasses(Embeddable.class)); classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class)); final List existingClasses = pu.getClazz(); for (Class clazz : classes) { final String name = clazz.getName(); if ((packageName == null || name.startsWith(packageName)) && !existingClasses.contains(name)) { pu.getClazz().add(name); } } pu.setScanned(true); } } } } return ejbModule; } private SessionType getSessionType(Class clazz) { if (clazz.isAnnotationPresent(Stateful.class)) return SessionType.STATEFUL; if (clazz.isAnnotationPresent(Stateless.class)) return SessionType.STATELESS; if (clazz.isAnnotationPresent(Singleton.class)) return SessionType.SINGLETON; if (clazz.isAnnotationPresent(ManagedBean.class)) return SessionType.MANAGED; return null; } private String getEjbName(EnterpriseBean bean, Class clazz) { if (bean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) bean; switch (sessionBean.getSessionType()) { case STATEFUL: { final Stateful annotation = clazz.getAnnotation(Stateful.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case STATELESS: { final Stateless annotation = clazz.getAnnotation(Stateless.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case SINGLETON: { final Singleton annotation = clazz.getAnnotation(Singleton.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } } } if (bean instanceof MessageDrivenBean) { final MessageDriven annotation = clazz.getAnnotation(MessageDriven.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } return clazz.getSimpleName(); } private static boolean specified(final String name) { return name != null && name.length() != 0; } private List getBeanClasses(IAnnotationFinder finder) { // What we're hoping in this method is to get lucky and find // that our 'finder' instances is an AnnotationFinder that is // holding an AggregatedArchive so we can get the classes that // that pertain to each URL for CDI purposes. // // If not we call finder.getAnnotatedClassNames() which may return // more classes than actually apply to CDI. This can "pollute" // the CDI class space and break injection points if (!(finder instanceof FinderFactory.ModuleLimitedFinder)) return finder.getAnnotatedClassNames(); final IAnnotationFinder delegate = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (!(delegate instanceof AnnotationFinder)) return finder.getAnnotatedClassNames(); final AnnotationFinder annotationFinder = (AnnotationFinder) delegate; final Archive archive = annotationFinder.getArchive(); if (!(archive instanceof WebappAggregatedArchive)) return finder.getAnnotatedClassNames(); final List classes = new ArrayList(); final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive; final Map> map = aggregatedArchive.getClassesMap(); for (Map.Entry> entry : map.entrySet()) { if (hasBeansXml(entry.getKey())) classes.addAll(entry.getValue()); } return classes; } public static boolean hasBeansXml(URL url) { if (url.getPath().endsWith("WEB-INF/classes/")) return true; if (url.getPath().endsWith("!/META-INF/beans.xml")) return true; try { final URLClassLoader loader = new URLClassLoader(new URL[]{ url } , new EmptyResourcesClassLoader()); String[] paths = { "META-INF/beans.xml", "WEB-INF/beans.xml", "/WEB-INF/beans.xml", "/META-INF/beans.xml", }; for (String path : paths) { if (loader.findResource(path) != null) return true; } } catch (Exception e) { } return false; } private String getEjbName(MessageDriven mdb, Class beanClass) { return (mdb.name().isEmpty() ? beanClass.getSimpleName() : mdb.name()); } private String getEjbName(Stateful stateful, Class beanClass) { return (stateful.name().isEmpty() ? beanClass.getSimpleName() : stateful.name()); } private String getEjbName(Stateless stateless, Class beanClass) { return (stateless.name().isEmpty() ? beanClass.getSimpleName() : stateless.name()); } private String getEjbName(Singleton singleton, Class beanClass) { return (singleton.name().isEmpty() ? beanClass.getSimpleName() : singleton.name()); } private String getEjbName(ManagedBean managed, Class beanClass) { return (managed.value().isEmpty() ? beanClass.getSimpleName() : managed.value()); } private boolean isValidEjbAnnotationUsage(Class annotationClass, Annotated> beanClass, String ejbName, EjbModule ejbModule) { List> annotations = new ArrayList(asList(Singleton.class, Stateless.class, Stateful.class, MessageDriven.class)); annotations.remove(annotationClass); boolean b = true; for (Class secondAnnotation : annotations) { Annotation annotation = beanClass.getAnnotation(secondAnnotation); if (annotation == null) continue; String secondEjbName = null; if (annotation instanceof Stateful) { secondEjbName = getEjbName((Stateful) annotation, beanClass.get()); } else if (annotation instanceof Stateless) { secondEjbName = getEjbName((Stateless) annotation, beanClass.get()); } else if (annotation instanceof Singleton) { secondEjbName = getEjbName((Singleton) annotation, beanClass.get()); } else if (annotation instanceof MessageDriven) { secondEjbName = getEjbName((MessageDriven) annotation, beanClass.get()); } if (ejbName.equals(secondEjbName)) { ejbModule.getValidation().fail(ejbName, "multiplyAnnotatedAsBean", annotationClass.getSimpleName(), secondAnnotation.getSimpleName(), ejbName, beanClass.get().getName()); } } // not a dynamic proxy implemented bean if (beanClass.getAnnotation(PersistenceContext.class) == null && beanClass.getAnnotation(Proxy.class) == null && beanClass.get().isInterface()) { ejbModule.getValidation().fail(ejbName, "interfaceAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } if (!beanClass.get().isInterface() && isAbstract(beanClass.get().getModifiers())) { ejbModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } return b; } } |
blob | " "} | f | f | f | " "} | blob | 0 | 12693 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/config/AnnotationDeployer.java/#L411-L1700 | 1 | 4726 | 12693 | critical |
| 1608 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XPathParser { private final Map prefixes = new HashMap(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // for compatibility return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } } |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 11455 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/sax/xpath/XPathParser.java/#L40-L120 | 1 | 1608 | 11455 | minor |
| 774 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } } |
blob | data class | t | t | f | data class | blob | 0 | 7350 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 | 1 | 774 | 7350 | major |
| 1964 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 12590 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 1964 | 12590 | minor |
| 2529 | {"response": "YES I found bad smells", "bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14731 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 1 | 2529 | 14731 | minor |
| 4293 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11322 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 1 | 4293 | 11322 | minor | ||
| 297 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplication of code, 3. Complex code, 4. Feature envy, 5. Inconsistent naming conventions, 6. Poor abstraction, 7. Mixing of different responsibilities in one class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | Long method, 2 Duplication of code, 3 Complex code, 4 Feature envy, 5 Inconsistent naming conventions, 6 Poor abstraction, 7 Mixing of different responsibilities in one class | t | f | f | . Long method, 2. Duplication of code, 3. Complex code, 4. Feature envy, 5. Inconsistent naming conventions, 6. Poor abstraction, 7. Mixing of different responsibilities in one class. | blob | 0 | 3123 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 2 | 297 | 3123 | minor |
| 5732 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 13493 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5732 | 13493 | critical |
| 2518 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 14704 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 2 | 2518 | 14704 | major |
| 174 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2045 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 174 | 2045 | minor |
| 85 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Step deleteJobAsync( String name, String namespace, V1DeleteOptions deleteOptions, ResponseStep responseStep) { return createRequestAsync( responseStep, new RequestParams("deleteJob", namespace, name, deleteOptions), DELETE_JOB); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 1212 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L991-L998 | 1 | 85 | 1212 | minor |
| 3424 | { "output": "YES I found bad smells", "the bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AppService implements ApplicationService { private static final Logger logger = LoggerFactory.getLogger(ApplicationService.class); /** * Create an register an application service using the default alias {@link ApplicationService#ALIAS}. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @return Application service instance. */ public static ApplicationService createAndRegister(TopologyProvider provider, DirectSubmitter submitter) { AppService service = new AppService(provider, submitter, ALIAS); submitter.getServices().addService(ApplicationService.class, service); return service; } private final Map> applications = Collections.synchronizedMap(new HashMap<>()); private final TopologyProvider provider; private final DirectSubmitter submitter; /** * Create an {@code ApplicationService} instance. * @param provider Provider to create topology instances for registered applications. * @param submitter Submitter for registered applications. * @param alias Alias used to register the control MBean. */ public AppService(TopologyProvider provider, DirectSubmitter submitter, String alias) { this.provider = provider; this.submitter = submitter; ControlService cs = submitter.getServices().getService(ControlService.class); if (cs != null) cs.registerControl(ApplicationServiceMXBean.TYPE, ALIAS+System.currentTimeMillis(), alias, ApplicationServiceMXBean.class, new AppServiceControl(this)); } @Override public void registerTopology(String applicationName, BiConsumer builder) { if (applicationName == null || applicationName.isEmpty()) { throw new IllegalArgumentException(); } logger.trace("Register application name: {}", applicationName); applications.put(applicationName, builder); } /** * Create a new class loader for the jar and register any * topology application that is registered as a service provider. */ @Override public void registerJar(String jarURL, String jsonConfig) throws Exception { logger.trace("Register jar: {}", jarURL); // If it's a http URL download it otherwise use directly. URL url = new URL(jarURL); String protocol = url.getProtocol(); if ("http".equals(protocol) || "https".equals(protocol)) { url = downloadJar(url); } URLClassLoader loader = new URLClassLoader(new URL[] {url}); for (TopologyBuilder topoBuilder : ServiceLoader.load(TopologyBuilder.class, loader)) { registerTopology(topoBuilder.getName(), topoBuilder.getBuilder()); } } /** * Download an HTTP URL to a local file. * @param url URL to download from. * @return URL of the local file. */ private URL downloadJar(URL url) throws Exception { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Error response code for URL: {} : response code={}", url.toExternalForm(), responseCode); throw new IOException(); } String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); if (disposition != null) { // extracts file name from header field int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name from URL path String path = url.getPath(); if (!path.isEmpty()) { int lastSlash = path.lastIndexOf("/"); if (lastSlash == -1) fileName = path; else fileName = path.substring(lastSlash+1); } } // TODO - allow persistence across reboots // For now just store in a temp directory Path dir = Files.createTempDirectory("edgentjars"); File file; if (fileName.isEmpty()) file = File.createTempFile("edgent", "jar", dir.toFile()); else file = new File(dir.toFile(), fileName); InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); logger.trace("Register jar downloaded as: {}", file); return file.toURI().toURL(); } @Override public Set getApplicationNames() { synchronized (applications) { return new HashSet<>(applications.keySet()); } } BiConsumer getBuilder(String applicationName) { return applications.get(applicationName); } TopologyProvider getProvider() { return provider; } DirectSubmitter getSubmitter() { return submitter; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6745 | https://github.com/apache/incubator-edgent/blob/2e44089358175964650fed5e2bf4ad071b05b7d6/runtime/appservice/src/main/java/org/apache/edgent/runtime/appservice/AppService.java/#L62-L217 | 1 | 3424 | 6745 | minor |
| 2048 | { "error": "Sorry, I cannot analyze the provided Java code to identify bad smells. You may want to use a specialized code analysis tool for this task." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | f | f | f | long method | 0 | 12878 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 2048 | 12878 | major | ||
| 868 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 7947 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 868 | 7947 | minor |
| 1023 | YES I found bad smells the bad smell are: 1.Feature envy (dataPlan, bestPlan) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Feature envy (dataPlan, bestPlan) | t | f | f | .Feature envy (dataPlan, bestPlan) | data class | 0 | 9353 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1023 | 9353 | major |
| 1827 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } } |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 12115 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 | 1 | 1827 | 12115 | minor |
| 1567 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11329 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 2 | 1567 | 11329 | minor |
| 1639 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11533 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 1 | 1639 | 11533 | minor | ||
| 2458 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Comments","3. Use of deprecated methods","4. High method complexity","5. Lack of encapsulation","6. Mixing of concerns"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | '1. Long method', '2. Comments', '3. Use of deprecated methods', '4. High method complexity', '5. Lack of encapsulation', '6. Mixing of concerns' | t | t | f | {',1,.," ",L,o,n,g," ",m,e,t,h,o,d,',","," ",',2,.," ",C,o,m,m,e,n,t,s,',","," ",',3,.," ",U,s,e," ",o,f," ",d,e,p,r,e,c,a,t,e,d," ",m,e,t,h,o,d,s,',","," ",',4,.," ",H,i,g,h," ",m,e,t,h,o,d," ",c,o,m,p,l,e,x,i,t,y,',","," ",',5,.," ",L,a,c,k," ",o,f," ",e,n,c,a,p,s,u,l,a,t,i,o,n,',","," ",',6,.," ",M,i,x,i,n,g," ",o,f," ",c,o,n,c,e,r,n,s,'} | {',1,.," ",o,n,g," ",m,t,h,o,d,',","," ",',2,.," ",C,o,m,m,n,t,',","," ",',3,.," ",U," ",o," ",d,p,r,c,t,d," ",m,t,h,o,d,',","," ",',4,.," ",H,i,g,h," ",m,t,h,o,d," ",c,o,m,p,x,i,t,y,',","," ",',5,.," ",c,k," ",o," ",n,c,p,u,t,i,o,n,',","," ",',6,.," ",M,i,x,i,n,g," ",o," ",c,o,n,c,r,n,'} | 0 | 14533 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 2 | 2458 | 14533 | minor |
| 3818 | { "output": "YES I found bad smells the bad smells are: 3. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | 3. long method | t | t | f | 3. long method | data class | 0 | 9732 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 1 | 3818 | 9732 | minor |
| 288 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 3061 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 288 | 3061 | critical |
| 498 | { "message": "YES I found bad smells" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 5045 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 2 | 498 | 5045 | minor |
| 1611 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | f | f | f | data class | 0 | 11463 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 1 | 1611 | 11463 | major | ||
| 259 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | long method | t | t | f | long method | data class | 0 | 2812 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 2 | 259 | 2812 | critical |
| 3811 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 9700 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 2 | 3811 | 9700 | minor | ||
| 176 | {"response": "YES I found bad smells. the bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface DedicatedService extends PluggableService { DedicatePodResponse createDedicatePodResponse(DedicatedResources resource); DedicateClusterResponse createDedicateClusterResponse(DedicatedResources resource); DedicateHostResponse createDedicateHostResponse(DedicatedResources resource); Pair, Integer> listDedicatedPods(ListDedicatedPodsCmd cmd); Pair, Integer> listDedicatedHosts(ListDedicatedHostsCmd cmd); Pair, Integer> listDedicatedClusters(ListDedicatedClustersCmd cmd); boolean releaseDedicatedResource(Long zoneId, Long podId, Long clusterId, Long hostId); DedicateZoneResponse createDedicateZoneResponse(DedicatedResources resource); Pair, Integer> listDedicatedZones(ListDedicatedZonesCmd cmd); List dedicateZone(Long zoneId, Long domainId, String accountName); List dedicatePod(Long podId, Long domainId, String accountName); List dedicateCluster(Long clusterId, Long domainId, String accountName); List dedicateHost(Long hostId, Long domainId, String accountName); } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2050 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/dedicated-resources/src/main/java/org/apache/cloudstack/dedicated/DedicatedService.java/#L35-L63 | 2 | 176 | 2050 | minor |
| 1406 | YES I found bad smells the bad smells are: 1. Long class, 2. Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand. 3. Duplicate code: the versions of Spark (e.g. SPARK_1_6_0, SPARK_2_0_0) are repeated multiple times in the code, leading to potential errors if they are not all updated consistently. 4. Inconsistent naming: some methods and fields use camelCase while others use snake_case, making the code inconsistent and harder to read. 5. Magic numbers: the version is calculated using a hardcoded number format, making it unclear what the number actually represents and making the code less maintainable. 6. Poor exception handling: the code uses a generic "catch-all" exception, which can hide potential errors and make debugging difficult. 7. Feature envy: some methods (e.g. toString(), isSpark2()) rely heavily on the state of the SparkVersion class, rather than on their own state. 8. Lack of encapsulation: the fields of the class (e.g. versionString, majorVersion) are declared as public, allowing them to be accessed and modified from outside the class. This breaks the principle of encapsulation and can lead to potential errors. 9. Mixing of concerns: the class handles both Spark versioning and logic related to detecting unsupported versions and supporting secret sockets. This can make the code more complex and harder to maintain. 10. Potential data inconsistency: because the class does not enforce any rules about how the versionNumber field should be updated when modifying the major, minor, or patch versions, it could lead to data inconsistency and potential bugs. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | Long class, 2 Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand3 Duplicate code: the versions of Spark (eg SPARK_ | t | f | f | . Long class, 2. Feature envy: the SparkVersion class has a very long list of methods and fields, making it difficult to navigate and understand.3. Duplicate code: the versions of Spark (e.g. SPARK_ | data class | 0 | 10877 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 2 | 1406 | 10877 | minor |
| 352 | Yes I found bad smells The bad smells are: 1. Magic numbers 2. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DBMsgConstants { public static final int MAX_BODY_SIZE = 64 * 1024 * 1024; //64KB } |
data class | Magic numbers2 Inconsistent naming conventions | t | f | f | . Magic numbers2. Inconsistent naming conventions | data class | 0 | 3605 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/constant/DBMsgConstants.java/#L20-L22 | 2 | 352 | 3605 | critical |
| 3848 | {"response": "YES, I found bad smells", "detected_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 30, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Thread) public static class DeleteTasksBenchmark { private StateManager manager; private Storage storage; private Set taskIds; @Param({"1000", "10000", "50000"}) private int numTasksToDelete; @Setup(Level.Trial) public void setUpStorage() { Injector injector = getInjector(); manager = injector.getInstance(StateManager.class); storage = injector.getInstance(Storage.class); storage.prepare(); } // JMH warns heavily against using `Invocation` but this test seems to meet the requirements // of using it. Each benchmark will take more than one ms and it avoids awkward logic to // setup storage before the benchmark. @Setup(Level.Invocation) public void setUp() { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(Storage.MutableStoreProvider storeProvider) throws RuntimeException { taskIds = bulkInsertTasks(numTasksToDelete, storeProvider.getUnsafeTaskStore()); } }); } @Benchmark public Set run() { return storage.write((Storage.MutateWork.Quiet>) storeProvider -> { manager.deleteTasks(storeProvider, taskIds); return taskIds; }); } } |
blob | long method | t | t | f | long method | blob | 0 | 9985 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/jmh/java/org/apache/aurora/benchmark/StateManagerBenchmarks.java/#L117-L159 | 1 | 3848 | 9985 | minor |
| 710 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionalManyTransitionImpl extends MinimalEObjectImpl.Container implements OptionalManyTransition { /** * The default value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected static final String VAL_EDEFAULT = null; /** * The cached value of the '{@link #getVal() Val}' attribute. * * * @see #getVal() * @generated * @ordered */ protected String val = VAL_EDEFAULT; /** * * * @generated */ protected OptionalManyTransitionImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SyntacticsequencertestPackage.Literals.OPTIONAL_MANY_TRANSITION; } /** * * * @generated */ public String getVal() { return val; } /** * * * @generated */ public void setVal(String newVal) { String oldVal = val; val = newVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL, oldVal, val)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return getVal(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: setVal(VAL_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SyntacticsequencertestPackage.OPTIONAL_MANY_TRANSITION__VAL: return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (val: "); result.append(val); result.append(')'); return result.toString(); } } //OptionalManyTransitionImpl |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 6764 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/syntacticsequencertest/impl/OptionalManyTransitionImpl.java/#L29-L178 | 2 | 710 | 6764 | minor |
| 2234 | {"response": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | data class | t | t | f | data class | blob | 0 | 13604 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 1 | 2234 | 13604 | minor |
| 2067 | -13 Long method the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 3 Long methodthe bad smells are: | f | f | f | 3 Long methodthe bad smells are: | data class | 0 | 12996 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 2067 | 12996 | minor |
| 4756 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WantPropertyElement extends Frame implements WantsObjectFrameI, HasSubjectFrameI { int liCounter = 1; ANode predicate; ANode object; ANode reify; boolean objectIsBlank = false; public WantPropertyElement(HasSubjectFrameI s, AbsXMLContext x) { super(s, x); } // These three are used as bitfields static final private int TYPEDLITERAL = 1; static final private int EMPTYWITHOBJ = 2; static final private int PARSETYPE = 4; @Override public FrameI startElement(String uri, String localName, String rawName, Attributes atts) throws SAXParseException { clearObject(); if (nonWhiteMsgGiven) taint.isTainted(); nonWhiteMsgGiven = false; if (uri==null || uri.equals("")) { warning(WARN_UNQUALIFIED_ELEMENT,"Unqualified property elements are not allowed. Treated as a relative URI."); } ElementLexer el = new ElementLexer(taint, this, uri, localName, rawName, E_LI, CoreAndOldTerms | E_DESCRIPTION, false); // if (el.badMatch) // warning(ERR_SYNTAX_ERROR,"bad use of " + rawName); predicate = el.goodMatch ? (AResourceInternal) rdf_n(liCounter++) : URIReference.fromQName(this, uri, localName); if (taint.isTainted()) predicate.taint(); taint = new TaintImpl(); AttributeLexer ap = new AttributeLexer(this, // xml: A_XMLLANG | A_XMLBASE | A_XML_OTHER // legal rdf: | A_DATATYPE | A_ID | A_NODEID | A_PARSETYPE | A_RESOURCE | A_TYPE, // bad rdf: A_BADATTRS); int cnt = ap.processSpecials(taint, atts); // These three states are intended as mutually // incompatible, but all three can occur // together. Any two of the three, or all // three is a syntax errror. // Having none of these is legal. final int nextStateCode = (ap.datatype == null ? 0 : TYPEDLITERAL) | (ap.parseType == null ? 0 : PARSETYPE) | (mustBeEmpty(ap, atts, cnt) ? EMPTYWITHOBJ : 0); if (this.badStateCode(nextStateCode)) { warning(errorNumber(nextStateCode), descriptionOfCases(ap, nextStateCode, propertyAttributeDescription(atts, ap, cnt))); } AbsXMLContext x = ap.xml(xml); reify = ap.id == null ? null : URIReference.fromID(this, x, ap.id); if (taint.isTainted()) predicate.taint(); if (mustBeEmpty(ap, atts, cnt)) { if (ap.nodeID != null) { object = new ARPResource(arp, ap.nodeID); checkNodeID_XMLName(object, ap.nodeID); objectIsBlank = true; } if (ap.resource != null) { if (object != null) { if (!badStateCode(nextStateCode)) // otherwise warning already given warning(ERR_SYNTAX_ERROR, "On a property element, only one of the attributes rdf:nodeID or rdf:resource is permitted."); } else object = URIReference.resolve(this, x, ap.resource); } if (object == null) { object = new ARPResource(arp); objectIsBlank = true; } if (taint.isTainted()) object.taint(); processPropertyAttributes(ap, atts, x); } FrameI nextFrame = nextFrame(atts, ap, cnt, nextStateCode, x); if (object != null) { if (taint.isTainted()) object.taint(); theObject(object); } if (taint.isTainted()) predicate.taint(); return nextFrame; } private boolean mustBeEmpty(AttributeLexer ap, Attributes atts, int cnt) { return cnt < atts.getLength() || ap.type != null || ap.nodeID != null || ap.resource != null; } private FrameI nextFrame(Attributes atts, AttributeLexer ap, int cnt, int nextStateCode, AbsXMLContext x) throws SAXParseException { switch (nextStateCode) { case 0: return new WantLiteralValueOrDescription(this, x); case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case PARSETYPE: return withParsetype(ap.parseType, x); case TYPEDLITERAL | EMPTYWITHOBJ: case TYPEDLITERAL: return new WantTypedLiteral(this, ap.datatype, x); case EMPTYWITHOBJ: return new WantEmpty(this, x); } throw new IllegalStateException("impossible"); } private FrameI withParsetype(String pt, AbsXMLContext x) throws SAXParseException { if (pt.equals("Collection")) { return new RDFCollection(this, x); } if (pt.equals("Resource")) { if (object == null) { // in some error cases the object has already been set. object = new ARPResource(arp); objectIsBlank = true; } return new WantPropertyElement(this, x); } if (!pt.equals("Literal")) { warning(WARN_UNKNOWN_PARSETYPE, "Unknown rdf:parseType: '" + pt + "' (treated as 'Literal'."); } return new OuterXMLLiteral(this, x, pt); } @Override String suggestParsetypeLiteral() { return (getParent() instanceof WantTopLevelDescription) ? "" : super .suggestParsetypeLiteral(); } @Override public void aPredAndObj(ANode p, ANode o) { triple(object, p, o); } @Override public void makeSubjectReificationWith(ANode r) { triple(r, RDF_SUBJECT, object); } @Override public void theObject(ANode o) { HasSubjectFrameI p = (HasSubjectFrameI) getParent(); p.aPredAndObj(predicate, o); if (reify != null) { triple(reify, RDF_TYPE, RDF_STATEMENT); triple(reify, RDF_OBJECT, o); triple(reify, RDF_PREDICATE, predicate); p.makeSubjectReificationWith(reify); } } @Override public void endElement() { clearObject(); } @Override public void abort() { clearObject(); } private void clearObject() { if (objectIsBlank) arp.endLocalScope(object); objectIsBlank = false; object = null; } static private URIReference _rdf_n[] = new URIReference[0]; static private URIReference rdf_n(int i) { if (i >= _rdf_n.length) { int newLength = (i + 10) * 3 / 2; URIReference new_rdf_n[] = new URIReference[newLength]; System.arraycopy(_rdf_n, 0, new_rdf_n, 0, _rdf_n.length); for (int j = _rdf_n.length; j < newLength; j++) { new_rdf_n[j] = URIReference.createNoChecks(rdfns + "_" + j); } _rdf_n = new_rdf_n; } return _rdf_n[i]; } /*************************************************************************** * * ERROR HANDLING CODE * **************************************************************************/ // Error detection private boolean badStateCode(int nextStateCode) { switch (nextStateCode) { case PARSETYPE | TYPEDLITERAL: case PARSETYPE | TYPEDLITERAL | EMPTYWITHOBJ: case PARSETYPE | EMPTYWITHOBJ: case TYPEDLITERAL | EMPTYWITHOBJ: return true; case 0: case PARSETYPE: case TYPEDLITERAL: case EMPTYWITHOBJ: return false; } throw new IllegalStateException("impossible"); } // Error classification private int errorNumber(int nextStateCode) { // TODO: not for 2.3. refine this error code. return ERR_SYNTAX_ERROR; } /*************************************************************************** * * ERROR MESSAGES * **************************************************************************/ private String descriptionOfCases(AttributeLexer ap, int nextStateCode, String propAttrs) { return ((propAttrs == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && ap.type == null) || (ap.nodeID == null && ap.resource == null && propAttrs == null)) ? pairwiseIncompatibleErrorMessage( nextStateCode, ap, propAttrs) : complicatedErrorMessage(nextStateCode, ap, propAttrs); } private String pairwiseIncompatibleErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { ArrayList cases = new ArrayList<>(); if ((nextStateCode & PARSETYPE) != 0) cases.add("rdf:parseType"); if ((nextStateCode & TYPEDLITERAL) != 0) cases.add("rdf:datatype"); if (ap.nodeID != null) cases.add("rdf:nodeID"); if (ap.resource != null) cases.add("rdf:resource"); if (ap.type != null) cases.add("rdf:type"); if (cases.size() == 1) { if (propAttrs == null) throw new IllegalStateException("Shouldn't happen."); return "The attribute " + cases.get(0) + " is not permitted with " + propAttrs + " on a property element."; } String rslt = "On a property element, only one of the "; if (propAttrs == null) rslt += "attributes "; for (int i = 0; i < cases.size(); i++) { rslt += cases.get(i); switch (cases.size() - i) { case 1: break; case 2: rslt += " or "; break; default: rslt += ", "; break; } } if (propAttrs != null) { rslt += " attributes or " + propAttrs; } rslt += " is permitted."; return rslt; } private String complicatedErrorMessage(int nextStateCode, AttributeLexer ap, String propAttrs) { String subjectIs; if (ap.nodeID == null && ap.resource == null && (ap.type == null || propAttrs == null)) throw new IllegalStateException("precondition failed."); switch (nextStateCode & (TYPEDLITERAL | PARSETYPE)) { case TYPEDLITERAL | PARSETYPE: subjectIs = "the mutually incompatible attributes rdf:datatype and rdf:parseType are"; break; case TYPEDLITERAL: subjectIs = "the attribute rdf:datatype is"; break; case PARSETYPE: subjectIs = "the attribute rdf:parseType is"; break; default: throw new IllegalStateException("precondition failed"); } String nodeIDResource = null; if (ap.nodeID != null && ap.resource != null) { nodeIDResource = "the mutually incompatible attributes rdf:nodeID and rdf:resource"; } else if (ap.nodeID != null) { nodeIDResource = "the attribute rdf:nodeID"; } else if (ap.resource != null) { nodeIDResource = "the attribute rdf:resource"; } int otherAttCount = nodeIDResource == null ? 0 : 1; String otherAtts; if (ap.type != null) otherAttCount++; if (propAttrs != null) otherAttCount++; if (otherAttCount < 2) throw new IllegalStateException("logic error"); otherAtts = otherAttCount == 2 ? "both " : "each of "; if (ap.type != null && propAttrs != null) { if (nodeIDResource == null) otherAtts += "the attribute rdf:type and the " + propAttrs; else otherAtts += "the attribute rdf:type, the " + propAttrs; } else if (ap.type != null) { otherAtts += "the attribute rdf:type"; } else { otherAtts = "the " + propAttrs; } if (nodeIDResource != null) otherAtts += " and "+nodeIDResource; return "On a property element, " + subjectIs + " incompatible with " + otherAtts +"."; } private String propertyAttributeDescription(Attributes atts, AttributeLexer ap, int cnt) { String propAttrs = ""; int propAttrCount = atts.getLength() - cnt; int found = 0; if (propAttrCount == 0) return null; switch (propAttrCount) { case 0: break; case 1: case 2: case 3: for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { propAttrs += atts.getQName(i); found++; switch (propAttrCount - found) { case 0: break; case 1: propAttrs += " and "; break; default: propAttrs += ", "; } } break; default: if (propAttrCount < 0) throw new IllegalStateException("Shouldn't happen."); for (int i = 0; i < atts.getLength(); i++) if (!ap.done(i)) { found++; switch (found) { case 1: propAttrs += atts.getQName(i) + ", "; break; case 2: propAttrs += atts.getQName(i) + ", ..."; break; default: // ignore } } } return "property attributes (" + propAttrs + ")"; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 12798 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/states/WantPropertyElement.java/#L27-L436 | 1 | 4756 | 12798 | minor |
| 477 | {"output":"YES, I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 4591 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 477 | 4591 | minor |
| 1458 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | blob | 0 | 11018 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 2 | 1458 | 11018 | minor |
| 4238 | "My answer: YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy" | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | Long method, 2 Feature envy" | t | f | f | . Long method, 2. Feature envy" | data class | 0 | 11157 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 4238 | 11157 | major |
| 1756 | YES I found bad smells The bad smells are: 1. Long method 2. Data class 3. Brain method 4. Feature envy 5. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
blob | Long method2 Data class3 Brain method4 Feature envy5 Large class | t | f | f | . Long method2. Data class3. Brain method4. Feature envy5. Large class | blob | 0 | 11876 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 1756 | 11876 | minor |
| 1505 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | f | f | f | data class | 0 | 11149 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 1505 | 11149 | major | ||
| 1160 | { "output": "YES I found bad smells the bad smells are: 1. Long method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 10164 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 1 | 1160 | 10164 | major |
| 985 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 8878 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 985 | 8878 | major |
| 1864 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | long method | t | t | f | long method | data class | 0 | 12232 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 2 | 1864 | 12232 | critical |
| 298 | YES I found bad smells the bad smells are: 1.Dead code, 2.The class is annotated as deprecated but it does not have any Deprecated annotation or comment. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Dead code, 2The class is annotated as deprecated but it does not have any Deprecated annotation or comment | t | f | f | .Dead code, 2.The class is annotated as deprecated but it does not have any Deprecated annotation or comment. | data class | 0 | 3132 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 298 | 3132 | major |
| 1611 | YES, I found bad smells The bad smells are: 1. Class not well-structured 2. Class fields not organized 3. No constructor or getter/setter methods 4. Inconsistent formatting of field declarations (some have equal signs, some have semi-colons) 5. Fields not marked as private or not properly encapsulated | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | Class not well-structured2 Class fields not organized3 No constructor or getter/setter methods4 Inconsistent formatting of field declarations (some have equal signs, some have semi-colons)5 Fields not marked as private or not properly encapsulated | t | f | f | . Class not well-structured2. Class fields not organized3. No constructor or getter/setter methods4. Inconsistent formatting of field declarations (some have equal signs, some have semi-colons)5. Fields not marked as private or not properly encapsulated | data class | 0 | 11463 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 1611 | 11463 | major |
| 2493 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Long method2 Feature Envy 3 Code duplication | t | f | f | . Long method2. Feature Envy 3. Code duplication | data class | 0 | 14624 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2493 | 14624 | minor |
| 1064 | YES I found bad smells The bad smells are: 1. Misleading variable names - key and val are not clear descriptors of the purpose of these variables. 2. Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods. 3. Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method. 4. Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class. 5. Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Misleading variable names - key and val are not clear descriptors of the purpose of these variables2 Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods3 Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method4 Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class5 Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class | t | f | f | . Misleading variable names - key and val are not clear descriptors of the purpose of these variables.2. Lack of encapsulation - the variables are declared as public instead of private and not accessed through setter or getter methods.3. Code duplication - the methods getEncodedKey() and getEncodedValue() have similar functionality and could be refactored into a single method.4. Primitive obsession - the class only contains primitive type variables and could benefit from using a more complex data type or creating a separate class.5. Possible feature envy - the encode() method is not a part of the Header class and could potentially be moved to a different class. | data class | 0 | 9556 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 1064 | 9556 | minor |
| 1759 | {"message": "YES I found bad smells the bad smells are:", "bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | t | f | f | data class | 0 | 11885 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 1759 | 11885 | minor | ||
| 2016 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue.Builder public abstract static class Builder { public abstract Builder setCompileTimeConstant(boolean compileTimeConstant); public abstract Builder setStatic(boolean isStatic); public abstract Builder setFinal(boolean isFinal); public abstract Builder setVariableCapture(boolean isVariableCapture); public abstract Builder setEnclosingInstanceCapture(boolean isEnclosingInstanceCapture); public abstract Builder setEnclosingTypeDescriptor( DeclaredTypeDescriptor enclosingTypeDescriptor); public abstract Builder setName(String name); public abstract Builder setEnumConstant(boolean isEnumConstant); public abstract Builder setSynthetic(boolean isSynthetic); public abstract Builder setTypeDescriptor(TypeDescriptor typeDescriptor); public abstract Builder setVisibility(Visibility visibility); public abstract Builder setJsInfo(JsInfo jsInfo); public abstract Builder setUnusableByJsSuppressed(boolean isUnusableByJsSuppressed); public abstract Builder setDeprecated(boolean isDeprecated); public abstract Builder setOrigin(FieldOrigin fieldOrigin); public Builder setDeclarationFieldDescriptor(FieldDescriptor declarationFieldDescriptor) { return setDeclarationFieldDescriptorOrNullIfSelf(declarationFieldDescriptor); } // Accessors to support validation, default construction and custom setters. abstract Builder setDeclarationFieldDescriptorOrNullIfSelf( FieldDescriptor declarationFieldDescriptor); abstract Optional getName(); abstract FieldDescriptor autoBuild(); public FieldDescriptor build() { checkState(getName().isPresent()); FieldDescriptor fieldDescriptor = autoBuild(); checkState( !fieldDescriptor.isVariableCapture() || !fieldDescriptor.isEnclosingInstanceCapture()); return interner.intern(fieldDescriptor); } public static Builder from(FieldDescriptor fieldDescriptor) { return fieldDescriptor.toBuilder(); } private static final ThreadLocalInterner interner = new ThreadLocalInterner<>(); } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 12770 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/ast/FieldDescriptor.java/#L194-L255 | 2 | 2016 | 12770 | minor |
| 5090 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 14228 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 2 | 5090 | 14228 | major |
| 1275 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number 3. Duplicate code 4. Temporary variable 5. Feature envy 6. Messages couples 7. Lazy class 8. Inappropriate intimacy 9. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | Long method2 Magic number3 Duplicate code4 Temporary variable5 Feature envy6 Messages couples7 Lazy class8 Inappropriate intimacy9 Primitive obsession | t | f | f | . Long method2. Magic number3. Duplicate code4. Temporary variable5. Feature envy6. Messages couples7. Lazy class8. Inappropriate intimacy9. Primitive obsession | blob | 0 | 10583 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 2 | 1275 | 10583 | minor |
| 1016 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 9303 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 2 | 1016 | 9303 | minor |
| 2429 | { "output": "YES I found bad smells", "bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextListenerStartup implements ServletContextListener { /** Configuration file path parameter name. */ public static final String IGNITE_CFG_FILE_PATH_PARAM = "IgniteConfigurationFilePath"; /** Names of started Ignite instances. */ private final Collection igniteInstanceNames = new ArrayList<>(); /** {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent evt) { ServletContext ctx = evt.getServletContext(); String cfgFile = ctx.getInitParameter(IGNITE_CFG_FILE_PATH_PARAM); Collection cfgs; GridSpringResourceContext rsrcCtx = null; if (cfgFile != null) { URL cfgUrl = null; try { cfgUrl = evt.getServletContext().getResource("/META-INF/" + cfgFile); } catch (MalformedURLException ignored) { // Ignore, we still need to try with IGNITE_HOME. } if (cfgUrl == null) // Try with IGNITE_HOME and with context class loader. cfgUrl = U.resolveIgniteUrl(cfgFile); if (cfgUrl == null) throw new IgniteException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile); IgniteBiTuple, ? extends GridSpringResourceContext> t; try { t = IgnitionEx.loadConfigurations(cfgUrl); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to load Ignite configuration.", e); } cfgs = t.get1(); rsrcCtx = t.get2(); if (cfgs.isEmpty()) throw new IgniteException("Can't find grid factory configuration in: " + cfgUrl); } else cfgs = Collections.singleton(new IgniteConfiguration()); try { assert !cfgs.isEmpty(); for (IgniteConfiguration cfg : cfgs) { assert cfg != null; Ignite ignite; synchronized (ServletContextListenerStartup.class) { try { ignite = G.ignite(cfg.getIgniteInstanceName()); } catch (IgniteIllegalStateException ignored) { ignite = IgnitionEx.start(new IgniteConfiguration(cfg), rsrcCtx); } } // Check if grid is not null - started properly. if (ignite != null) igniteInstanceNames.add(ignite.name()); } } catch (IgniteCheckedException e) { // Stop started grids only. for (String name : igniteInstanceNames) G.stop(name, true); throw new IgniteException("Failed to start Ignite.", e); } } /** {@inheritDoc} */ @Override public void contextDestroyed(ServletContextEvent evt) { // Stop started grids only. for (String name: igniteInstanceNames) G.stop(name, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ServletContextListenerStartup.class, this); } } |
blob | 1: long method | t | t | f | 1: long method | blob | 0 | 14453 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/web/src/main/java/org/apache/ignite/startup/servlet/ServletContextListenerStartup.java/#L95-L189 | 1 | 2429 | 14453 | minor |
| 122 | {"output": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Data static class VaultInitializationResponseImpl implements VaultInitializationResponse { private List keys = new ArrayList<>(); @JsonProperty("root_token") private String rootToken = ""; public VaultToken getRootToken() { return VaultToken.of(rootToken); } } |
data class | Not specified | f | f | f | false | 0 | 1535 | https://github.com/spring-projects/spring-vault/blob/6e36eb10b02c6931c3b565c5d9d76f5e217bf309/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java/#L414-L425 | 2 | 122 | 1535 | major | |
| 1250 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10436 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1250 | 10436 | critical |
| 2316 | YES I found bad smells the bad smells are: 1. Long method 2. Parallel inheritance hierarchies | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | Long method 2 Parallel inheritance hierarchies | t | f | f | . Long method 2. Parallel inheritance hierarchies | feature envy | 0 | 14118 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 2316 | 14118 | minor |
| 1482 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11083 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 2 | 1482 | 11083 | minor |
| 1610 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
blob | t | f | f | blob | 0 | 11459 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 1 | 1610 | 11459 | minor | ||
| 1905 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 12371 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 2 | 1905 | 12371 | minor |
| 2331 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14153 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 2331 | 14153 | minor |
| 943 | YES I found bad smells the bad smells are: 1.Features envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
blob | Features envy | t | f | f | .Features envy | blob | 0 | 8473 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 943 | 8473 | minor |
| 1284 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10606 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 1284 | 10606 | major |
| 3946 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 10325 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 | 2 | 3946 | 10325 | critical | ||
| 1292 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10621 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 1292 | 10621 | major |
| 2364 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | Long method,2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 14255 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 2364 | 14255 | minor |
| 688 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } } |
data class | long method | t | t | f | long method | data class | 0 | 6634 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 | 1 | 688 | 6634 | major |
| 4197 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11045 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 4197 | 11045 | critical |
| 1507 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11152 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 1 | 1507 | 11152 | critical |
| 2526 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14723 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 2 | 2526 | 14723 | minor |
| 1902 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12364 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 1902 | 12364 | minor |
| 1593 | {"message": "YES I found bad smells", "bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
blob | t | f | f | blob | 0 | 11406 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 1593 | 11406 | minor | ||
| 150 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 1904 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 150 | 1904 | major |
| 942 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ResultSet getUpdateVTIResultSet(NoPutResultSet source) throws StandardException { Activation activation = source.getActivation(); getAuthorizer(activation).authorize(activation, Authorizer.SQL_WRITE_OP); return new UpdateVTIResultSet(source, activation); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8465 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/GenericResultSetFactory.java/#L188-L194 | 1 | 942 | 8465 | minor |
| 447 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4364 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 2 | 447 | 4364 | critical |
| 2547 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14792 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 2547 | 14792 | minor |
| 156 | {"message": "YES, I found bad smells", "smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ArgumentProcessor getProcessor( Class< ? extends ArgumentProcessor> processorClass) { ArgumentProcessor processor; try { processor = processorClass.getConstructor().newInstance(); } catch (Exception e) { throw new BuildException("The argument processor class" + processorClass.getName() + " could not be instantiated with a default constructor", e); } return processor; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1968 | https://github.com/apache/ant/blob/9722f062dc68d6c321faf751621162ac8444c585/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java/#L121-L133 | 1 | 156 | 1968 | minor |
| 1308 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10677 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 1 | 1308 | 10677 | minor |
| 264 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2866 | https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 | 2 | 264 | 2866 | minor |
| 1819 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 12093 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 | 1 | 1819 | 12093 | minor |
| 3814 | YES I found bad smells the bad smells are: 1.Magic number, 2.Inconsistent naming Convention, 3.Inconsistent formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ClasspathUriUtil { public static final String CLASSPATH_SCHEME = "classpath"; public static boolean isClasspathUri(URI uri) { if (uri == null) return false; String scheme = uri.scheme(); return CLASSPATH_SCHEME.equals(scheme); } } |
data class | Magic number, 2Inconsistent naming Convention, 3Inconsistent formatting | t | f | f | .Magic number, 2.Inconsistent naming Convention, 3.Inconsistent formatting | data class | 0 | 9713 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/resource/ClasspathUriUtil.java/#L20-L31 | 2 | 3814 | 9713 | minor |
| 410 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DIRuntimeException extends RuntimeException { private static final long serialVersionUID = 396131653561690312L; /** * Creates new ConfigurationException without detail message. */ public DIRuntimeException() { } /** * Constructs an exception with the specified message with an optional list * of message formatting arguments. Message formatting rules follow * "String.format(..)" conventions. */ public DIRuntimeException(String messageFormat, Object... messageArgs) { super(String.format(messageFormat, messageArgs)); } /** * Constructs an exception wrapping another exception thrown elsewhere. */ public DIRuntimeException(Throwable cause) { super(cause); } public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) { super(String.format(messageFormat, messageArgs), cause); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4172 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-di/src/main/java/org/apache/cayenne/di/DIRuntimeException.java/#L26-L55 | 2 | 410 | 4172 | minor |
| 786 | {"message":"YES. I found bad smells","bad smells":[ "1. Long method", "2. Long method", "3. Long method", "4. Long method", "5. Long method", "6. Long method", "7. Long method", "8. Long method", "9. Feature envy" ]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | 1. long method, 2. long method, 3. long method, 4. long method, 5. long method, 6. long method, 7. long method, 8. long method, 9. feature envy | t | t | f | 1. long method, 2. long method, 3. long method, 4. long method, 5. long method, 6. long method, 7. long method, 8. long method, 9. feature envy | blob | 0 | 7505 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 2 | 786 | 7505 | minor |
| 1691 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } } |
blob | Data Class | t | f | f | Data Class | blob | 0 | 11710 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 | 1 | 1691 | 11710 | minor |
| 413 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OsgiRequirementAdapter implements Requirement { private static final Logger logger = LoggerFactory.getLogger(OsgiRequirementAdapter.class); private final org.osgi.resource.Requirement requirement; public OsgiRequirementAdapter(org.osgi.resource.Requirement requirement) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); this.requirement = requirement; } public String getComment() { return null; } public String getFilter() { return requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); } public String getName() { return NamespaceTranslator.translate(requirement.getNamespace()); } public boolean isExtend() { return false; } public boolean isMultiple() { String multiple = requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE); return Namespace.CARDINALITY_MULTIPLE.equals(multiple); } public boolean isOptional() { String resolution = requirement.getDirectives().get(Constants.RESOLUTION_DIRECTIVE); return Constants.RESOLUTION_OPTIONAL.equals(resolution); } public boolean isSatisfied(Capability capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); boolean result = ResourceHelper.matches(requirement, new FelixCapabilityAdapter(capability, null)); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4217 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiRequirementAdapter.java/#L28-L72 | 2 | 413 | 4217 | major |
| 2026 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement with repeated code 3. Use of raw type 4. Magic number/unnamed constants 5. Use of multiple return statements within a method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
feature envy | Long method2 Switch statement with repeated code3 Use of raw type4 Magic number/unnamed constants5 Use of multiple return statements within a method | t | f | f | . Long method2. Switch statement with repeated code3. Use of raw type4. Magic number/unnamed constants5. Use of multiple return statements within a method | feature envy | 0 | 12803 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 2 | 2026 | 12803 | minor |
| 348 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inappropriate inheritance hierarchy 4. Duplicate code 5. Lack of encapsulation 6. Unused variables 7. Magic numbers 8. Poor exception handling 9. Lack of consistency 10. Overcomplicated code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TraversalFieldAccessorFactory implements FieldAccessorFactory { @Override public boolean accept(final Neo4JPersistentProperty f) { final GraphTraversal graphEntityTraversal = f.getAnnotation(GraphTraversal.class); return graphEntityTraversal != null && graphEntityTraversal.traversalBuilder() != FieldTraversalDescriptionBuilder.class && f.getType().equals(Iterable.class); } @Override public FieldAccessor forField(final Neo4JPersistentProperty property) { return new TraversalFieldAccessor(property); } /** * @author Michael Hunger * @since 12.09.2010 */ public static class TraversalFieldAccessor implements FieldAccessor { protected final Neo4JPersistentProperty property; private final FieldTraversalDescriptionBuilder fieldTraversalDescriptionBuilder; private Class target; protected String[] params; public TraversalFieldAccessor(final Neo4JPersistentProperty property) { this.property = property; final GraphTraversal graphEntityTraversal = property.getAnnotation(GraphTraversal.class); this.target = resolveTarget(graphEntityTraversal,property); this.params = graphEntityTraversal.params(); this.fieldTraversalDescriptionBuilder = createTraversalDescription(graphEntityTraversal); } private Class resolveTarget(GraphTraversal graphTraversal, Neo4JPersistentProperty property) { if (!graphTraversal.elementClass().equals(NodeBacked.class)) return graphTraversal.elementClass(); final Class result = property.getTypeInformation().getActualType().getType(); Class[] allowedTypes={NodeBacked.class,RelationshipBacked.class,Node.class,Relationship.class, Path.class}; if (!checkTypes(result,allowedTypes)) throw new IllegalArgumentException("The target result type "+result+" of the traversal is no subclass of the allowed types: "+property+" "+allowedTypes); return result; } private boolean checkTypes(Class target, Class...allowedTypes) { for (Class type : allowedTypes) { if (type.isAssignableFrom(target)) return true; } return false; } @Override public boolean isWriteable(NodeBacked nodeBacked) { return false; } @Override public Object setValue(final NodeBacked nodeBacked, final Object newVal) { throw new InvalidDataAccessApiUsageException("Cannot set readonly traversal description field " + property); } @Override public Object getValue(final NodeBacked nodeBacked) { final TraversalDescription traversalDescription = fieldTraversalDescriptionBuilder.build(nodeBacked, property,params); return doReturn(nodeBacked.findAllByTraversal(target, traversalDescription)); } private FieldTraversalDescriptionBuilder createTraversalDescription(final GraphTraversal graphEntityTraversal) { try { final Class traversalDescriptionClass = graphEntityTraversal.traversalBuilder(); final Constructor constructor = traversalDescriptionClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating TraversalDescription from " + property,e); } } @Override public Object getDefaultImplementation() { return null; } } } |
blob | Long method2 Feature envy3 Inappropriate inheritance hierarchy4 Duplicate code5 Lack of encapsulation 6 Unused variables7 Magic numbers8 Poor exception handling9 Lack of consistency | t | f | f | . Long method2. Feature envy3. Inappropriate inheritance hierarchy4. Duplicate code5. Lack of encapsulation 6. Unused variables7. Magic numbers8. Poor exception handling9. Lack of consistency | blob | 0 | 3559 | https://github.com/spring-projects/spring-data-graph/blob/0210210ce436eb83bf200f5d5f9a63a440c5b27a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/fieldaccess/TraversalFieldAccessorFactory.java/#L36-L119 | 2 | 348 | 3559 | minor |
| 112 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1463 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 2 | 112 | 1463 | major |
| 831 | { "output": "YES, I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | \n1. long method\n2. feature envy | t | t | f | \\n1. long method\\n2. feature envy | blob | 0 | 7738 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 2 | 831 | 7738 | critical |
| 2218 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13542 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 2 | 2218 | 13542 | minor |
| 1648 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | 1. data class | t | t | f | 1. data class | feature envy | 0 | 11565 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 1 | 1648 | 11565 | major |
| 1036 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 9403 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 2 | 1036 | 9403 | minor |
| 356 | YES I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 3676 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 2 | 356 | 3676 | major |
| 225 | {"response": "YES, I found bad smells", "bad smells are:": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2434 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 2 | 225 | 2434 | minor |
| 1163 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10179 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 2 | 1163 | 10179 | minor |
| 2031 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12811 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 1 | 2031 | 12811 | minor |
| 51 | {"message": "YES I found bad smells", "bad smells are:": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ForeachCommand extends Command { public static String[] foreachArgs = null; public ForeachCommand() { addCommand("foreach", "", "build up a list of elements to operate on "); addCommand("do", "", "repeat a command for each element in the list"); } public void run(String command, final String[] args, final Context context, final PrintStream out) throws DDRInteractiveCommandException { if (command.equals("!do")) { boolean echo = false; boolean quiet = false; String token = null; int commandIndex = 0; while (commandIndex < args.length) { if (args[commandIndex].equals("help")) { out.println("The !do command is used to repeat a command on the elements gathered by the !foreach command."); out.println("Syntax: !do [echo] [quiet] [token=] [args]"); out.println(); out.println("\techo\t\tOutput each command before it is run."); out.println("\tquiet\t\tSuppress delimiters between command outputs."); out.println("\ttoken=\tSpecify a substitution token. Occurrencs of this string in the args will be replaced by the current element."); return; } else if (args[commandIndex].equals("echo")) { echo = true; commandIndex += 1; } else if (args[commandIndex].equals("quiet")) { quiet = true; commandIndex += 1; } else if (args[commandIndex].startsWith("token=")) { token = args[commandIndex].substring("token=".length()); commandIndex += 1; } else { break; } } if (commandIndex >= args.length) { out.println("The do command requires another command to repeat."); return; } if ((null == foreachArgs) || (0 == foreachArgs.length)) { out.println("Element list is empty. Use the foreach command to populate it."); return; } for (int i = 0; i < foreachArgs.length; i++) { if (!quiet && (i > 0)) { out.println("========================================"); } try { String[] newArgs; if (null == token) { newArgs = substituteArgs(args, commandIndex, i); } else { newArgs = substituteArgs(args, commandIndex, i, token); } if (echo) { System.out.println("> " + args[commandIndex] + " " + Arrays.toString(newArgs)); } CommandParser commandParser = new CommandParser(args[commandIndex], newArgs); context.execute(commandParser, out); } catch (ParseException e) { e.printStackTrace(out); } catch (Throwable th) { out.println("Exception while executing " + args[commandIndex] + " " + foreachArgs[i]); th.printStackTrace(out); } } } else if(command.equals("!foreach")) { if (args.length > 0) { out.println("The !foreach command takes no arguments, but will read lines from the console until it encounters a blank line."); out.println("These lines can then be used as arguments to commands specified using !do."); return; } ArrayList lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (0 == line.length()) { break; } else { lines.add(line); } } // split by , String[] newArgs = new String[lines.size()]; lines.toArray(newArgs); foreachArgs = newArgs; } } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex) { /* Concatenate: * */ String[] newArgs = new String[args.length - commandIndex]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); newArgs[newArgs.length - 1] = foreachArgs[foreachIndex]; return newArgs; } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex, String token) { /* Concatenate: * * Replacing any occurence of token with */ String[] newArgs = new String[args.length - commandIndex - 1]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); for (int i = 0; i < newArgs.length; i++) { newArgs[i] = newArgs[i].replace(token, foreachArgs[foreachIndex]); } return newArgs; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 872 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/tools/ddrinteractive/commands/ForeachCommand.java/#L37-L165 | 2 | 51 | 872 | minor |
| 2564 | YES I found bad smells. the bad smells are: 1. Magic number 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Magic number2 Feature envy | t | f | f | . Magic number2. Feature envy | data class | 0 | 14847 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 2564 | 14847 | minor |
| 1907 | {"answer": "YES I found bad smells", "detected_bad_smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12386 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 1 | 1907 | 12386 | critical |
| 892 | YES I found bad smells the bad smells are: 1.Long method, 2.Switch statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | Long method, 2Switch statement | t | f | f | .Long method, 2.Switch statement | feature envy | 0 | 8106 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 2 | 892 | 8106 | minor |
| 1408 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10885 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 1 | 1408 | 10885 | minor |
| 2448 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14498 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 2448 | 14498 | minor |
| 174 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2045 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 174 | 2045 | minor |
| 2282 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13839 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 2 | 2282 | 13839 | major |
| 5275 | . There are no major bad smells in this code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 14747 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5275 | 14747 | minor | ||
| 644 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 6355 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 644 | 6355 | major |
| 4956 | { "status": "success", "message": "YES, I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 13562 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 4956 | 13562 | minor |
| 835 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
blob | long method | t | t | f | long method | blob | 0 | 7750 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 1 | 835 | 7750 | major |
| 3862 | YES I found bad smells. Bad smells are: 1. Long methods - the class contains a lot of getters, setters, and methods with similar functionality. 2. Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | Long methods - the class contains a lot of getters, setters, and methods with similar functionality2 Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class | t | f | f | . Long methods - the class contains a lot of getters, setters, and methods with similar functionality.2. Feature envy - the class is more concerned with manipulating data rather than performing specific actions or behaviors related to a specific shape entity, indicating data and behavior should be better encapsulated within a Shape class. | data class | 0 | 10055 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 2 | 3862 | 10055 | critical |
| 919 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 8258 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 1 | 919 | 8258 | major |
| 728 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6853 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 728 | 6853 | major |
| 1760 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
blob | t | f | f | blob | 0 | 11890 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 1760 | 11890 | minor | ||
| 1289 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | long method | t | t | f | long method | data class | 0 | 10615 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 1289 | 10615 | major |
| 799 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7571 | https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/.mvn/wrapper/MavenWrapperDownloader.java/#L25-L110 | 2 | 799 | 7571 | minor |
| 4135 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | f | f | f | data class | 0 | 10881 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 4135 | 10881 | major | ||
| 4311 | YES I found bad smells The bad smells are: 1. Feature envy, 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
blob | Feature envy, 2 Long method | t | f | f | . Feature envy, 2. Long method | blob | 0 | 11363 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 4311 | 11363 | minor |
| 1990 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data clumps 4. Duplicate code 5. Inappropriate naming 6. Inconsistent formatting 7. Too many parameters in constructor 8. Magic numbers 9. Repeated conditional logic 10. Use of primitive data types instead of classes 11. Nesting and complexity in methods 12. Inefficient algorithms or data structures. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } } |
blob | Long method2 Feature envy3 Data clumps4 Duplicate code5 Inappropriate naming6 Inconsistent formatting7 Too many parameters in constructor8 Magic numbers9 Repeated conditional logic | t | f | f | . Long method2. Feature envy3. Data clumps4. Duplicate code5. Inappropriate naming6. Inconsistent formatting7. Too many parameters in constructor8. Magic numbers9. Repeated conditional logic | blob | 0 | 12680 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 | 2 | 1990 | 12680 | major |
| 3548 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7729 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 3548 | 7729 | minor | ||
| 1155 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
feature envy | the bad smells are: long method | t | t | f | the bad smells are: long method | feature envy | 0 | 10138 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 1155 | 10138 | critical |
| 576 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5781 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 2 | 576 | 5781 | major |
| 588 | {"message": "YES I found bad smells", "the bad smells are": ["1.Long method", "2.Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } } |
blob | 1.long method, 2.feature envy | t | t | f | 1.long method, 2.feature envy | blob | 0 | 5858 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 | 2 | 588 | 5858 | critical |
| 319 | {"message": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetAgent extends Agent { //---------------------navigational members----------------------------------- // All these request objects point to the same physical request object. ConnectionRequestInterface connectionRequest_; StatementRequestInterface statementRequest_; ResultSetRequestInterface resultSetRequest_; // All these reply objects point to the same physical reply object. ConnectionReply connectionReply_; private ConnectionReply packageReply_; StatementReply statementReply_; ResultSetReply resultSetReply_; //---------------------navigational cheat-links------------------------------- // Cheat-links are for convenience only, and are not part of the conceptual model. // Warning: // Cheat-links should only be defined for invariant state data. // That is, the state data is set by the constructor and never changes. // Alias for (NetConnection) super.connection NetConnection netConnection_; // Alias for (Request) super.*Request, all in one // In the case of the NET implementation, these all point to the same physical request object. private Request request_; NetConnectionRequest netConnectionRequest_; private NetPackageRequest netPackageRequest_; private NetStatementRequest netStatementRequest_; private NetResultSetRequest netResultSetRequest_; // Alias for (Reply) super.*Reply, all in one. // In the case of the NET implementation, these all point to the same physical reply object. private Reply reply_; NetConnectionReply netConnectionReply_; private NetPackageReply netPackageReply_; private NetStatementReply netStatementReply_; private NetResultSetReply netResultSetReply_; //-----------------------------state------------------------------------------ Socket socket_; private InputStream rawSocketInputStream_; private OutputStream rawSocketOutputStream_; String server_; int port_; private int clientSSLMode_; private EbcdicCcsidManager ebcdicCcsidManager_; private Utf8CcsidManager utf8CcsidManager_; private CcsidManager currentCcsidManager_; // TODO: Remove target? Keep just one CcsidManager? //public CcsidManager targetCcsidManager_; Typdef typdef_; Typdef targetTypdef_; Typdef originalTargetTypdef_; // added to support typdef overrides private int svrcod_; int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7; int targetSqlam_ = orignalTargetSqlam_; SqlException exceptionOpeningSocket_ = null; SqlException exceptionConvertingRdbnam = null; /** * Flag which indicates that a writeChain has been started and data sent to * the server. * If true, starting a new write chain will throw a DisconnectException. * It is cleared when the write chain is ended. */ private boolean writeChainIsDirty_ = false; //---------------------constructors/finalizer--------------------------------- // Only used for testing public NetAgent(NetConnection netConnection, LogWriter logWriter) throws SqlException { super(netConnection, logWriter); this.netConnection_ = netConnection; } NetAgent(NetConnection netConnection, LogWriter netLogWriter, int loginTimeout, String server, int port, int clientSSLMode) throws SqlException { super(netConnection, netLogWriter); server_ = server; port_ = port; netConnection_ = netConnection; clientSSLMode_ = clientSSLMode; if (server_ == null) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET), "serverName"); } try { socket_ = (Socket)AccessController.doPrivileged( new OpenSocketAction(server, port, clientSSLMode_)); } catch (PrivilegedActionException e) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER), e.getException(), e.getException().getClass().getName(), server, port, e.getException().getMessage()); } // Set TCP/IP Socket Properties try { if (exceptionOpeningSocket_ == null) { socket_.setTcpNoDelay(true); // disables nagles algorithm socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2 socket_.setSoTimeout(loginTimeout * 1000); } } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION), e, e.getMessage()); } try { if (exceptionOpeningSocket_ == null) { rawSocketOutputStream_ = socket_.getOutputStream(); rawSocketInputStream_ = socket_.getInputStream(); } } catch (IOException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM), e, e.getMessage()); } ebcdicCcsidManager_ = new EbcdicCcsidManager(); utf8CcsidManager_ = new Utf8CcsidManager(); currentCcsidManager_ = ebcdicCcsidManager_; if (netConnection_.isXAConnection()) { NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_); netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_; netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, netConnection_.commBufferSize_); netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_; netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } else { netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_); netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; netResultSetRequest_ = new NetResultSetRequest(this, netConnection_.commBufferSize_); netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } } protected void resetAgent_(LogWriter netLogWriter, //CcsidManager sourceCcsidManager, //CcsidManager targetCcsidManager, int loginTimeout, String server, int port) throws SqlException { exceptionConvertingRdbnam = null; // most properties will remain unchanged on connect reset. targetTypdef_ = originalTargetTypdef_; svrcod_ = 0; // Set TCP/IP Socket Properties try { socket_.setSoTimeout(loginTimeout * 1000); } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } throw new SqlException(logWriter_, new ClientMessageId(SQLState.SOCKET_EXCEPTION), e, e.getMessage()); } } void setSvrcod(int svrcod) { if (svrcod > svrcod_) { svrcod_ = svrcod; } } void clearSvrcod() { svrcod_ = CodePoint.SVRCOD_INFO; } private int getSvrcod() { return svrcod_; } public void flush_() throws DisconnectException { sendRequest(); reply_.initialize(); } // Close socket and its streams. public void close_() throws SqlException { // can we just close the socket here, do we need to close streams individually SqlException accumulatedExceptions = null; if (rawSocketInputStream_ != null) { try { rawSocketInputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes accumulatedExceptions = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); } finally { rawSocketInputStream_ = null; } } if (rawSocketOutputStream_ != null) { try { rawSocketOutputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { rawSocketOutputStream_ = null; } } if (socket_ != null) { try { socket_.close(); } catch (IOException e) { // again {6} = 0, indicates the socket was closed. // maybe set {4} to e.getMessage(). // do this for now and but may need to modify or // add this to the message pubs. SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { socket_ = null; } } if (accumulatedExceptions != null) { throw accumulatedExceptions; } } /** * Specifies the maximum blocking time that should be used when sending * and receiving messages. The timeout is implemented by using the the * underlying socket implementation's timeout support. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @param timeout The timeout value in seconds. A value of 0 corresponds to * infinite timeout. */ protected void setTimeout(int timeout) { try { // Sets a timeout on the socket socket_.setSoTimeout(timeout * 1000); // convert to milliseconds } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.setTimeout: ignoring exception: " + se); } } } /** * Returns the current timeout value that is set on the socket. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @return The timeout value in seconds. A value of 0 corresponds to * that no timeout is specified on the socket. */ protected int getTimeout() { int timeout = 0; // 0 is default timeout for sockets // Read the timeout currently set on the socket try { timeout = socket_.getSoTimeout(); } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.getTimeout: ignoring exception: " + se); } } // Convert from milliseconds to seconds (note that this truncates // the results towards zero but that should not be a problem). timeout = timeout / 1000; return timeout; } private void sendRequest() throws DisconnectException { try { request_.flush(rawSocketOutputStream_); } catch (IOException e) { throwCommunicationsFailure(e); } } public InputStream getInputStream() { return rawSocketInputStream_; } public CcsidManager getCurrentCcsidManager() { return currentCcsidManager_; } public OutputStream getOutputStream() { return rawSocketOutputStream_; } void setInputStream(InputStream inputStream) { rawSocketInputStream_ = inputStream; } void setOutputStream(OutputStream outputStream) { rawSocketOutputStream_ = outputStream; } void throwCommunicationsFailure(Throwable cause) throws DisconnectException { //DisconnectException //accumulateReadExceptionAndDisconnect // note when {6} = 0 it indicates the socket was closed. // need to still validate any token values against message publications. accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(this, new ClientMessageId(SQLState.COMMUNICATION_ERROR), cause, cause.getMessage())); } // ----------------------- call-down methods --------------------------------- protected void markChainBreakingException_() { setSvrcod(CodePoint.SVRCOD_ERROR); } public void checkForChainBreakingException_() throws SqlException { int svrcod = getSvrcod(); clearSvrcod(); if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker { super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one. } } private void writeDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.writeDeferredReset(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } /** * Marks the agent's write chain as dirty. A write chain is dirty when data * from it has been sent to the server. A dirty write chain cannot be reset * and reused for another request until the remaining data has been sent to * the server and the write chain properly ended. * * Resetting a dirty chain will cause the new request to be appended to the * unfinished request already at the server, which will likely lead to * cryptic syntax errors. */ void markWriteChainAsDirty() { writeChainIsDirty_ = true; } private void verifyWriteChainIsClean() throws DisconnectException { if (writeChainIsDirty_) { throw new DisconnectException(this, new ClientMessageId(SQLState.NET_WRITE_CHAIN_IS_DIRTY)); } } public void beginWriteChainOutsideUOW() throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); } public void beginWriteChain(ClientStatement statement) throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); super.beginWriteChain(statement); } protected void endWriteChain() {} private void readDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.readDeferredReset(); checkForExceptions(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } protected void beginReadChain(ClientStatement statement) throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChain(statement); } protected void beginReadChainOutsideUOW() throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChainOutsideUOW(); } /** * Switches the current CCSID manager to UTF-8 */ void switchToUtf8CcsidMgr() { currentCcsidManager_ = utf8CcsidManager_; } /** * Switches the current CCSID manager to EBCDIC */ void switchToEbcdicMgr() { currentCcsidManager_ = ebcdicCcsidManager_; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 3272 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.client/org/apache/derby/client/net/NetAgent.java/#L43-L550 | 2 | 319 | 3272 | minor |
| 878 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8012 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 878 | 8012 | critical |
| 2441 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
blob | long method | t | t | f | long method | blob | 0 | 14481 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 1 | 2441 | 14481 | minor |
| 1209 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | 1. long method, 2. blob | t | t | f | 1. long method, 2. blob | data class | 0 | 10306 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 1 | 1209 | 10306 | minor |
| 2474 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Exception handling should be improved 5. Inconsistent and unclear naming 6. Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
data class | Long method2 Feature envy3 Duplicate code 4 Exception handling should be improved 5 Inconsistent and unclear naming 6 Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Exception handling should be improved 5. Inconsistent and unclear naming 6. Code smells related to exception handling (for example, throwing generic exceptions instead of appropriate ones) | data class | 0 | 14583 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 2 | 2474 | 14583 | minor |
| 508 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 5157 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 2 | 508 | 5157 | minor |
| 2073 | {"response": "YES I found bad smells", "bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | long method | t | t | f | long method | data class | 0 | 13034 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 2 | 2073 | 13034 | minor |
| 4040 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10682 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 4040 | 10682 | major |
| 773 | YES I found bad smells the bad smells are: 1. Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object. 2. Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods. 3. Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code. 4. Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors. 5. Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls. 6. Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object2 Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods3 Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code4 Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors5 Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls6 Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain | t | f | f | . Feature envy: The methods getIconMap(), getIcon(), and getIcons() all seem to belong more to the LocalCollection object than the FacesProperty object.2. Duplicated code: The LocalCollection object is initialized and used multiple times in the getIconMap() and getIcons() methods.3. Shotgun surgery: If modifications need to be made to the Text or LocalCollection objects, they will have to be made in multiple places in the code.4. Long parameter list: The constructor for FacesProperty takes in a large number of parameters, which may make it difficult to manage and potentially lead to errors.5. Message chains: The methods getIcon(), getIconMap(), and getIcons() all rely on calling methods from the LocalCollection object, creating a long chain of object method calls.6. Inappropriate intimacy: The FacesProperty class has access to and manipulates objects from the Text and LocalCollection classes, which could potentially lead to tight coupling and make the code more difficult to understand and maintain. | data class | 0 | 7288 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 773 | 7288 | minor |
| 626 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Long Method", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GenericsUtils { public static final GenericsType[] EMPTY_GENERICS_ARRAY = GenericsType.EMPTY_ARRAY; public static final String JAVA_LANG_OBJECT = "java.lang.Object"; /** * Given a parameterized type and a generic type information, aligns actual type parameters. For example, if a * class uses generic type <T,U,V> (redirectGenericTypes), is used with actual type parameters * <java.lang.String, U,V>, then a class or interface using generic types <T,V> * will be aligned to <java.lang.String,V> * * @param redirectGenericTypes the type arguments or the redirect class node * @param parameterizedTypes the actual type arguments used on this class node * @param alignmentTarget the generic type arguments to which we want to align to * @return aligned type arguments * @deprecated You shouldn't call this method because it is inherently unreliable */ @Deprecated public static GenericsType[] alignGenericTypes(final GenericsType[] redirectGenericTypes, final GenericsType[] parameterizedTypes, final GenericsType[] alignmentTarget) { if (alignmentTarget == null) return EMPTY_GENERICS_ARRAY; if (parameterizedTypes == null || parameterizedTypes.length == 0) return alignmentTarget; GenericsType[] generics = new GenericsType[alignmentTarget.length]; for (int i = 0, scgtLength = alignmentTarget.length; i < scgtLength; i++) { final GenericsType currentTarget = alignmentTarget[i]; GenericsType match = null; if (redirectGenericTypes != null) { for (int j = 0; j < redirectGenericTypes.length && match == null; j++) { GenericsType redirectGenericType = redirectGenericTypes[j]; if (redirectGenericType.isCompatibleWith(currentTarget.getType())) { if (currentTarget.isPlaceholder() && redirectGenericType.isPlaceholder() && !currentTarget.getName().equals(redirectGenericType.getName())) { // check if there's a potential better match boolean skip = false; for (int k = j + 1; k < redirectGenericTypes.length && !skip; k++) { GenericsType ogt = redirectGenericTypes[k]; if (ogt.isPlaceholder() && ogt.isCompatibleWith(currentTarget.getType()) && ogt.getName().equals(currentTarget.getName())) { skip = true; } } if (skip) continue; } match = parameterizedTypes[j]; if (currentTarget.isWildcard()) { // if alignment target is a wildcard type // then we must make best effort to return a parameterized // wildcard ClassNode lower = currentTarget.getLowerBound() != null ? match.getType() : null; ClassNode[] currentUpper = currentTarget.getUpperBounds(); ClassNode[] upper = currentUpper != null ? new ClassNode[currentUpper.length] : null; if (upper != null) { for (int k = 0; k < upper.length; k++) { upper[k] = currentUpper[k].isGenericsPlaceHolder() ? match.getType() : currentUpper[k]; } } match = new GenericsType(ClassHelper.makeWithoutCaching("?"), upper, lower); match.setWildcard(true); } } } } if (match == null) { match = currentTarget; } generics[i] = match; } return generics; } /** * Generates a wildcard generic type in order to be used for checks against class nodes. * See {@link GenericsType#isCompatibleWith(org.codehaus.groovy.ast.ClassNode)}. * * @param types the type to be used as the wildcard upper bound * @return a wildcard generics type */ public static GenericsType buildWildcardType(final ClassNode... types) { ClassNode base = ClassHelper.makeWithoutCaching("?"); GenericsType gt = new GenericsType(base, types, null); gt.setWildcard(true); return gt; } public static Map extractPlaceholders(ClassNode cn) { Map ret = new HashMap(); extractPlaceholders(cn, ret); return ret; } /** * For a given classnode, fills in the supplied map with the parameterized * types it defines. * * @param node the class node to check * @param map the generics type information collector */ public static void extractPlaceholders(ClassNode node, Map map) { if (node == null) return; if (node.isArray()) { extractPlaceholders(node.getComponentType(), map); return; } if (!node.isUsingGenerics() || !node.isRedirectNode()) return; GenericsType[] parameterized = node.getGenericsTypes(); if (parameterized == null || parameterized.length == 0) return; GenericsType[] redirectGenericsTypes = node.redirect().getGenericsTypes(); if (redirectGenericsTypes == null || (node.isGenericsPlaceHolder() && redirectGenericsTypes.length != parameterized.length) /* GROOVY-8609 */ ) { redirectGenericsTypes = parameterized; } if (redirectGenericsTypes.length != parameterized.length) { throw new GroovyBugError("Expected earlier checking to detect generics parameter arity mismatch" + "\nExpected: " + node.getName() + toGenericTypesString(redirectGenericsTypes) + "\nSupplied: " + node.getName() + toGenericTypesString(parameterized)); } List valueList = new LinkedList<>(); for (int i = 0; i < redirectGenericsTypes.length; i++) { GenericsType redirectType = redirectGenericsTypes[i]; if (redirectType.isPlaceholder()) { GenericsTypeName name = new GenericsTypeName(redirectType.getName()); if (!map.containsKey(name)) { GenericsType value = parameterized[i]; map.put(name, value); valueList.add(value); } } } for (GenericsType value : valueList) { if (value.isWildcard()) { ClassNode lowerBound = value.getLowerBound(); if (lowerBound != null) { extractPlaceholders(lowerBound, map); } ClassNode[] upperBounds = value.getUpperBounds(); if (upperBounds != null) { for (ClassNode upperBound : upperBounds) { extractPlaceholders(upperBound, map); } } } else if (!value.isPlaceholder()) { extractPlaceholders(value.getType(), map); } } } public static String toGenericTypesString(GenericsType[] genericsTypes) { if (genericsTypes == null) return ""; StringBuilder sb = new StringBuilder("<"); for (int i = 0, n = genericsTypes.length; i < n; i++) { sb.append(genericsTypes[i].toString()); if (i < n - 1) { sb.append(","); } } sb.append("> "); return sb.toString(); } /** * Interface class nodes retrieved from {@link org.codehaus.groovy.ast.ClassNode#getInterfaces()} * or {@link org.codehaus.groovy.ast.ClassNode#getAllInterfaces()} are returned with generic type * arguments. This method allows returning a parameterized interface given the parameterized class * node which implements this interface. * * @param hint the class node where generics types are parameterized * @param target the interface we want to parameterize generics types * @return a parameterized interface class node * @deprecated Use #parameterizeType instead */ @Deprecated public static ClassNode parameterizeInterfaceGenerics(final ClassNode hint, final ClassNode target) { return parameterizeType(hint, target); } /** * Interface class nodes retrieved from {@link org.codehaus.groovy.ast.ClassNode#getInterfaces()} * or {@link org.codehaus.groovy.ast.ClassNode#getAllInterfaces()} are returned with generic type * arguments. This method allows returning a parameterized interface given the parameterized class * node which implements this interface. * * @param hint the class node where generics types are parameterized * @param target the interface we want to parameterize generics types * @return a parameterized interface class node */ public static ClassNode parameterizeType(final ClassNode hint, final ClassNode target) { if (hint.isArray()) { if (target.isArray()) { return parameterizeType(hint.getComponentType(), target.getComponentType()).makeArray(); } return target; } if (!target.equals(hint) && implementsInterfaceOrIsSubclassOf(target, hint)) { ClassNode nextSuperClass = ClassHelper.getNextSuperClass(target, hint); if (!hint.equals(nextSuperClass)) { Map genericsSpec = createGenericsSpec(hint); extractSuperClassGenerics(hint, nextSuperClass, genericsSpec); ClassNode result = correctToGenericsSpecRecurse(genericsSpec, nextSuperClass); return parameterizeType(result, target); } } Map genericsSpec = createGenericsSpec(hint); ClassNode targetRedirect = target.redirect(); genericsSpec = createGenericsSpec(targetRedirect, genericsSpec); extractSuperClassGenerics(hint, targetRedirect, genericsSpec); return correctToGenericsSpecRecurse(genericsSpec, targetRedirect); } public static ClassNode nonGeneric(ClassNode type) { if (type.isUsingGenerics()) { final ClassNode nonGen = ClassHelper.makeWithoutCaching(type.getName()); nonGen.setRedirect(type); nonGen.setGenericsTypes(null); nonGen.setUsingGenerics(false); return nonGen; } if (type.isArray() && type.getComponentType().isUsingGenerics()) { return type.getComponentType().getPlainNodeReference().makeArray(); } return type; } public static ClassNode newClass(ClassNode type) { return type.getPlainNodeReference(); } public static ClassNode makeClassSafe(Class klass) { return makeClassSafeWithGenerics(ClassHelper.make(klass)); } public static ClassNode makeClassSafeWithGenerics(Class klass, ClassNode genericsType) { GenericsType[] genericsTypes = new GenericsType[1]; genericsTypes[0] = new GenericsType(genericsType); return makeClassSafeWithGenerics(ClassHelper.make(klass), genericsTypes); } public static ClassNode makeClassSafe0(ClassNode type, GenericsType... genericTypes) { ClassNode plainNodeReference = newClass(type); if (genericTypes != null && genericTypes.length > 0) { plainNodeReference.setGenericsTypes(genericTypes); if (type.isGenericsPlaceHolder()) plainNodeReference.setGenericsPlaceHolder(true); } return plainNodeReference; } public static ClassNode makeClassSafeWithGenerics(ClassNode type, GenericsType... genericTypes) { if (type.isArray()) { return makeClassSafeWithGenerics(type.getComponentType(), genericTypes).makeArray(); } GenericsType[] gtypes = GenericsType.EMPTY_ARRAY; if (genericTypes != null) { gtypes = new GenericsType[genericTypes.length]; System.arraycopy(genericTypes, 0, gtypes, 0, gtypes.length); } return makeClassSafe0(type, gtypes); } public static MethodNode correctToGenericsSpec(Map genericsSpec, MethodNode mn) { ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType()); Parameter[] origParameters = mn.getParameters(); Parameter[] newParameters = new Parameter[origParameters.length]; for (int i = 0; i < origParameters.length; i++) { Parameter origParameter = origParameters[i]; newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression()); } return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode()); } public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type) { return correctToGenericsSpecRecurse(genericsSpec, type, new ArrayList()); } /** * @since 2.4.1 */ public static ClassNode[] correctToGenericsSpecRecurse(Map genericsSpec, ClassNode[] types) { if (types == null || types.length == 1) return types; ClassNode[] newTypes = new ClassNode[types.length]; boolean modified = false; for (int i = 0; i < types.length; i++) { newTypes[i] = correctToGenericsSpecRecurse(genericsSpec, types[i], new ArrayList()); modified = modified || (types[i] != newTypes[i]); } if (!modified) return types; return newTypes; } public static ClassNode correctToGenericsSpecRecurse(Map genericsSpec, ClassNode type, List exclusions) { if (type.isArray()) { return correctToGenericsSpecRecurse(genericsSpec, type.getComponentType(), exclusions).makeArray(); } if (type.isGenericsPlaceHolder() && !exclusions.contains(type.getUnresolvedName())) { String name = type.getGenericsTypes()[0].getName(); type = genericsSpec.get(name); if (type != null && type.isGenericsPlaceHolder() && type.getGenericsTypes() == null) { ClassNode placeholder = ClassHelper.makeWithoutCaching(type.getUnresolvedName()); placeholder.setGenericsPlaceHolder(true); type = makeClassSafeWithGenerics(type, new GenericsType(placeholder)); } } if (type == null) type = ClassHelper.OBJECT_TYPE; GenericsType[] oldgTypes = type.getGenericsTypes(); GenericsType[] newgTypes = GenericsType.EMPTY_ARRAY; if (oldgTypes != null) { newgTypes = new GenericsType[oldgTypes.length]; for (int i = 0; i < newgTypes.length; i++) { GenericsType oldgType = oldgTypes[i]; if (oldgType.isPlaceholder()) { if (genericsSpec.get(oldgType.getName()) != null) { newgTypes[i] = new GenericsType(genericsSpec.get(oldgType.getName())); } else { newgTypes[i] = new GenericsType(ClassHelper.OBJECT_TYPE); } } else if (oldgType.isWildcard()) { ClassNode oldLower = oldgType.getLowerBound(); ClassNode lower = oldLower != null ? correctToGenericsSpecRecurse(genericsSpec, oldLower, exclusions) : null; ClassNode[] oldUpper = oldgType.getUpperBounds(); ClassNode[] upper = null; if (oldUpper != null) { upper = new ClassNode[oldUpper.length]; for (int j = 0; j < oldUpper.length; j++) { upper[j] = correctToGenericsSpecRecurse(genericsSpec, oldUpper[j], exclusions); } } GenericsType fixed = new GenericsType(oldgType.getType(), upper, lower); fixed.setName(oldgType.getName()); fixed.setWildcard(true); newgTypes[i] = fixed; } else { newgTypes[i] = new GenericsType(correctToGenericsSpecRecurse(genericsSpec, correctToGenericsSpec(genericsSpec, oldgType), exclusions)); } } } return makeClassSafeWithGenerics(type, newgTypes); } public static ClassNode correctToGenericsSpec(Map genericsSpec, GenericsType type) { ClassNode ret = null; if (type.isPlaceholder()) { String name = type.getName(); ret = genericsSpec.get(name); } if (ret == null) ret = type.getType(); return ret; } public static ClassNode correctToGenericsSpec(Map genericsSpec, ClassNode type) { if (type.isArray()) { return correctToGenericsSpec(genericsSpec, type.getComponentType()).makeArray(); } if (type.isGenericsPlaceHolder()) { String name = type.getGenericsTypes()[0].getName(); type = genericsSpec.get(name); } if (type == null) type = ClassHelper.OBJECT_TYPE; return type; } @SuppressWarnings("unchecked") public static Map createGenericsSpec(ClassNode current) { return createGenericsSpec(current, Collections.EMPTY_MAP); } public static Map createGenericsSpec(ClassNode current, Map oldSpec) { Map ret = new HashMap(oldSpec); // ret contains the type specs, what we now need is the type spec for the // current class. To get that we first apply the type parameters to the // current class and then use the type names of the current class to reset // the map. Example: // class A{} // class B extends A {} // first we have: T->Number // we apply it to A -> A // resulting in: V->Number,W->Long,X->String GenericsType[] sgts = current.getGenericsTypes(); if (sgts != null) { ClassNode[] spec = new ClassNode[sgts.length]; for (int i = 0; i < spec.length; i++) { spec[i] = correctToGenericsSpec(ret, sgts[i]); } GenericsType[] newGts = current.redirect().getGenericsTypes(); if (newGts == null) return ret; ret.clear(); for (int i = 0; i < spec.length; i++) { ret.put(newGts[i].getName(), spec[i]); } } return ret; } public static Map addMethodGenerics(MethodNode current, Map oldSpec) { Map ret = new HashMap(oldSpec); // ret starts with the original type specs, now add gts for the current method if any GenericsType[] sgts = current.getGenericsTypes(); if (sgts != null) { for (GenericsType sgt : sgts) { String name = sgt.getName(); if (sgt.isPlaceholder()) { ClassNode redirect; if (sgt.getUpperBounds() != null) { redirect = sgt.getUpperBounds()[0]; } else if (sgt.getLowerBound() != null) { redirect = sgt.getLowerBound(); } else { redirect = ClassHelper.OBJECT_TYPE; } ClassNode type = ClassHelper.makeWithoutCaching(name); type.setGenericsPlaceHolder(true); type.setRedirect(redirect); ret.put(name, type); } else { ret.put(name, sgt.getType()); } } } return ret; } public static void extractSuperClassGenerics(ClassNode type, ClassNode target, Map spec) { // TODO: this method is very similar to StaticTypesCheckingSupport#extractGenericsConnections, // but operates on ClassNodes instead of GenericsType if (target == null || type == target) return; if (type.isArray() && target.isArray()) { extractSuperClassGenerics(type.getComponentType(), target.getComponentType(), spec); } else if (type.isArray() && JAVA_LANG_OBJECT.equals(target.getName())) { // Object is superclass of arrays but no generics involved } else if (target.isGenericsPlaceHolder() || type.equals(target) || !implementsInterfaceOrIsSubclassOf(type, target)) { // structural match route if (target.isGenericsPlaceHolder()) { spec.put(target.getGenericsTypes()[0].getName(), type); } else { extractSuperClassGenerics(type.getGenericsTypes(), target.getGenericsTypes(), spec); } } else { // have first to find matching super class or interface ClassNode superClass = getSuperClass(type, target); if (superClass != null) { ClassNode corrected = getCorrectedClassNode(type, superClass, false); extractSuperClassGenerics(corrected, target, spec); } else { // if we reach here, we have an unhandled case throw new GroovyBugError("The type " + type + " seems not to normally extend " + target + ". Sorry, I cannot handle this."); } } } public static ClassNode getSuperClass(ClassNode type, ClassNode target) { ClassNode superClass = ClassHelper.getNextSuperClass(type, target); if (superClass == null) { if (ClassHelper.isPrimitiveType(type)) { superClass = ClassHelper.getNextSuperClass(ClassHelper.getWrapper(type), target); } } return superClass; } private static void extractSuperClassGenerics(GenericsType[] usage, GenericsType[] declaration, Map spec) { // if declaration does not provide generics, there is no connection to make if (usage == null || declaration == null || declaration.length == 0) return; if (usage.length != declaration.length) return; // both have generics for (int i = 0; i < usage.length; i++) { GenericsType ui = usage[i]; GenericsType di = declaration[i]; if (di.isPlaceholder()) { spec.put(di.getName(), ui.getType()); } else if (di.isWildcard()) { if (ui.isWildcard()) { extractSuperClassGenerics(ui.getLowerBound(), di.getLowerBound(), spec); extractSuperClassGenerics(ui.getUpperBounds(), di.getUpperBounds(), spec); } else { ClassNode cu = ui.getType(); extractSuperClassGenerics(cu, di.getLowerBound(), spec); ClassNode[] upperBounds = di.getUpperBounds(); if (upperBounds != null) { for (ClassNode cn : upperBounds) { extractSuperClassGenerics(cu, cn, spec); } } } } else { extractSuperClassGenerics(ui.getType(), di.getType(), spec); } } } private static void extractSuperClassGenerics(ClassNode[] usage, ClassNode[] declaration, Map spec) { if (usage == null || declaration == null || declaration.length == 0) return; // both have generics for (int i = 0; i < usage.length; i++) { ClassNode ui = usage[i]; ClassNode di = declaration[i]; if (di.isGenericsPlaceHolder()) { spec.put(di.getGenericsTypes()[0].getName(), di); } else if (di.isUsingGenerics()) { extractSuperClassGenerics(ui.getGenericsTypes(), di.getGenericsTypes(), spec); } } } public static ClassNode[] parseClassNodesFromString( final String option, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage) { GroovyLexer lexer = new GroovyLexer(new StringReader("DummyNode<" + option + ">")); final GroovyRecognizer rn = GroovyRecognizer.make(lexer); try { rn.classOrInterfaceType(true); final AtomicReference ref = new AtomicReference(); AntlrParserPlugin plugin = new AntlrParserPlugin() { @Override public ModuleNode buildAST(final SourceUnit sourceUnit, final ClassLoader classLoader, final Reduction cst) throws ParserException { ref.set(makeTypeWithArguments(rn.getAST())); return null; } }; plugin.buildAST(null, null, null); ClassNode parsedNode = ref.get(); // the returned node is DummyNode genericsSpec, GenericsType[] oldPlaceHolders) { if (oldPlaceHolders == null || oldPlaceHolders.length == 0) return oldPlaceHolders; if (genericsSpec.isEmpty()) return oldPlaceHolders; GenericsType[] newTypes = new GenericsType[oldPlaceHolders.length]; for (int i = 0; i < oldPlaceHolders.length; i++) { GenericsType old = oldPlaceHolders[i]; if (!old.isPlaceholder()) throw new GroovyBugError("Given generics type " + old + " must be a placeholder!"); ClassNode fromSpec = genericsSpec.get(old.getName()); if (fromSpec != null) { if (fromSpec.isGenericsPlaceHolder()) { ClassNode[] upper = new ClassNode[]{fromSpec.redirect()}; newTypes[i] = new GenericsType(fromSpec, upper, null); } else { newTypes[i] = new GenericsType(fromSpec); } } else { ClassNode[] upper = old.getUpperBounds(); ClassNode[] newUpper = upper; if (upper != null && upper.length > 0) { ClassNode[] upperCorrected = new ClassNode[upper.length]; for (int j = 0; j < upper.length; j++) { upperCorrected[i] = correctToGenericsSpecRecurse(genericsSpec, upper[j]); } upper = upperCorrected; } ClassNode lower = old.getLowerBound(); ClassNode newLower = correctToGenericsSpecRecurse(genericsSpec, lower); if (lower == newLower && upper == newUpper) { newTypes[i] = oldPlaceHolders[i]; } else { ClassNode newPlaceHolder = ClassHelper.make(old.getName()); GenericsType gt = new GenericsType(newPlaceHolder, newUpper, newLower); gt.setPlaceholder(true); newTypes[i] = gt; } } } return newTypes; } private static final String TRUE_STR = "true"; private static final boolean PARAMETERIZED_TYPE_CACHE_ENABLED = TRUE_STR.equals(SystemUtil.getSystemPropertySafe("groovy.enable.parameterized.type.cache", TRUE_STR)); /** * Try to get the parameterized type from the cache. * If no cached item found, cache and return the result of {@link #findParameterizedType(ClassNode, ClassNode, boolean)} */ public static ClassNode findParameterizedTypeFromCache(final ClassNode genericsClass, final ClassNode actualType, boolean tryToFindExactType) { if (!PARAMETERIZED_TYPE_CACHE_ENABLED) { return findParameterizedType(genericsClass, actualType, tryToFindExactType); } SoftReference sr = PARAMETERIZED_TYPE_CACHE.getAndPut(new ParameterizedTypeCacheKey(genericsClass, actualType), key -> new SoftReference<>(findParameterizedType(key.getGenericsClass(), key.getActualType(), tryToFindExactType))); return null == sr ? null : sr.get(); } /** * Get the parameterized type by search the whole class hierarchy according to generics class and actual receiver. * {@link #findParameterizedTypeFromCache(ClassNode, ClassNode, boolean)} is strongly recommended for better performance. * * @param genericsClass the generics class * @param actualType the actual type * @param tryToFindExactType whether to try to find exact type * @return the parameterized type */ public static ClassNode findParameterizedType(ClassNode genericsClass, ClassNode actualType, boolean tryToFindExactType) { ClassNode parameterizedType = null; if (null == genericsClass.getGenericsTypes()) { return parameterizedType; } GenericsType[] declaringGenericsTypes = genericsClass.getGenericsTypes(); List classNodeList = new LinkedList<>(getAllSuperClassesAndInterfaces(actualType)); classNodeList.add(0, actualType); LinkedList parameterizedTypeCandidateList = new LinkedList<>(); for (ClassNode cn : classNodeList) { if (cn == genericsClass) { continue; } if (tryToFindExactType && null != cn.getGenericsTypes() && hasNonPlaceHolders(cn)) { parameterizedTypeCandidateList.add(cn); } if (!(genericsClass.equals(cn.redirect()))) { continue; } if (isGenericsTypeArraysLengthEqual(declaringGenericsTypes, cn.getGenericsTypes())) { parameterizedType = cn; break; } } if (null == parameterizedType) { if (!parameterizedTypeCandidateList.isEmpty()) { parameterizedType = parameterizedTypeCandidateList.getLast(); } } return parameterizedType; } private static boolean isGenericsTypeArraysLengthEqual(GenericsType[] declaringGenericsTypes, GenericsType[] actualGenericsTypes) { return null != actualGenericsTypes && declaringGenericsTypes.length == actualGenericsTypes.length; } private static List getAllSuperClassesAndInterfaces(ClassNode actualReceiver) { List superClassAndInterfaceList = new LinkedList<>(); List allSuperClassNodeList = getAllUnresolvedSuperClasses(actualReceiver); superClassAndInterfaceList.addAll(allSuperClassNodeList); superClassAndInterfaceList.addAll(actualReceiver.getAllInterfaces()); for (ClassNode superClassNode : allSuperClassNodeList) { superClassAndInterfaceList.addAll(superClassNode.getAllInterfaces()); } return superClassAndInterfaceList; } private static List getAllUnresolvedSuperClasses(ClassNode actualReceiver) { List superClassNodeList = new LinkedList<>(); for (ClassNode cn = actualReceiver.getUnresolvedSuperClass(); null != cn && ClassHelper.OBJECT_TYPE != cn; cn = cn.getUnresolvedSuperClass()) { superClassNodeList.add(cn); } return superClassNodeList; } private static final EvictableCache> PARAMETERIZED_TYPE_CACHE = new ConcurrentSoftCache<>(64); /** * Clear the parameterized type cache * It is useful to IDE as the type being compiled are continuously being edited/altered, see GROOVY-8675 */ public static void clearParameterizedTypeCache() { PARAMETERIZED_TYPE_CACHE.clearAll(); } /** * map declaring generics type to actual generics type, e.g. GROOVY-7204: * declaring generics types: T, S extends Serializable * actual generics types : String, Long * * the result map is [ * T: String, * S: Long * ] * * The resolved types can not help us to choose methods correctly if the argument is a string: T: Object, S: Serializable * so we need actual types: T: String, S: Long */ public static Map makeDeclaringAndActualGenericsTypeMap(ClassNode declaringClass, ClassNode actualReceiver) { return doMakeDeclaringAndActualGenericsTypeMap(declaringClass, actualReceiver, false).getV1(); } /** * The method is similar with {@link GenericsUtils#makeDeclaringAndActualGenericsTypeMap(ClassNode, ClassNode)}, * The main difference is that the method will try to map all placeholders found to the relevant exact types, * but the other will not try even if the parameterized type has placeholders * * @param declaringClass the generics class node declaring the generics types * @param actualReceiver the sub-class class node * @return the placeholder-to-actualtype mapping * @since 3.0.0 */ public static Map makeDeclaringAndActualGenericsTypeMapOfExactType(ClassNode declaringClass, ClassNode actualReceiver) { List parameterizedTypeList = new LinkedList<>(); Map result = makeDeclaringAndActualGenericsTypeMapOfExactType(declaringClass, actualReceiver, parameterizedTypeList); return connectGenericsTypes(result); } private static Map makeDeclaringAndActualGenericsTypeMapOfExactType(ClassNode declaringClass, ClassNode actualReceiver, List parameterizedTypeList) { Tuple2, ClassNode> resultAndParameterizedTypeTuple = doMakeDeclaringAndActualGenericsTypeMap(declaringClass, actualReceiver, true); ClassNode parameterizedType = resultAndParameterizedTypeTuple.getV2(); Map result = resultAndParameterizedTypeTuple.getV1(); if (hasPlaceHolders(parameterizedType) && !parameterizedTypeList.contains(parameterizedType)) { parameterizedTypeList.add(parameterizedType); result.putAll(makeDeclaringAndActualGenericsTypeMapOfExactType(parameterizedType, actualReceiver, parameterizedTypeList)); } return connectGenericsTypes(result); } private static Tuple2, ClassNode> doMakeDeclaringAndActualGenericsTypeMap(ClassNode declaringClass, ClassNode actualReceiver, boolean tryToFindExactType) { ClassNode parameterizedType = findParameterizedTypeFromCache(declaringClass, actualReceiver, tryToFindExactType); if (null == parameterizedType) { return tuple(Collections.emptyMap(), parameterizedType); } Map result = new LinkedHashMap<>(); result.putAll(makePlaceholderAndParameterizedTypeMap(declaringClass)); result.putAll(makePlaceholderAndParameterizedTypeMap(parameterizedType)); result = connectGenericsTypes(result); return tuple(result, parameterizedType); } private static Map makePlaceholderAndParameterizedTypeMap(ClassNode declaringClass) { if (null == declaringClass) { return Collections.emptyMap(); } Map result = new LinkedHashMap<>(); ClassNode redirectDeclaringClass = declaringClass.redirect(); GenericsType[] declaringGenericsTypes = declaringClass.getGenericsTypes(); GenericsType[] redirectDeclaringGenericsTypes = redirectDeclaringClass.getGenericsTypes(); if (null != declaringGenericsTypes && null != redirectDeclaringGenericsTypes) { for (int i = 0, n = declaringGenericsTypes.length; i < n; i++) { result.put(redirectDeclaringGenericsTypes[i], declaringGenericsTypes[i]); } } return result; } private static Map connectGenericsTypes(Map genericsTypeMap) { Map result = new LinkedHashMap<>(); outter: for (Map.Entry entry : genericsTypeMap.entrySet()) { GenericsType key = entry.getKey(); GenericsType value = entry.getValue(); if (value.isPlaceholder()) { for (Map.Entry genericsTypeMapEntry : genericsTypeMap.entrySet()) { GenericsType genericsTypeMapEntryValue = genericsTypeMapEntry.getValue(); if (!genericsTypeMapEntryValue.isPlaceholder() && (genericsTypeMapEntry.getKey().getName().equals(value.getName()))) { result.put(key, genericsTypeMapEntryValue); // connected to actual type continue outter; } } } result.put(key, value); } return result; } /** * Check whether the ClassNode has non generics placeholders, aka not placeholder * * @param parameterizedType the class node * @return the result * @since 3.0.0 */ public static boolean hasNonPlaceHolders(ClassNode parameterizedType) { return checkPlaceHolders(parameterizedType, genericsType -> !genericsType.isPlaceholder()); } /** * Check whether the ClassNode has generics placeholders * @param parameterizedType the class node * @return the result * @since 3.0.0 */ public static boolean hasPlaceHolders(ClassNode parameterizedType) { return checkPlaceHolders(parameterizedType, genericsType -> genericsType.isPlaceholder()); } private static boolean checkPlaceHolders(ClassNode parameterizedType, Predicate p) { if (null == parameterizedType) return false; GenericsType[] genericsTypes = parameterizedType.getGenericsTypes(); if (null == genericsTypes) return false; for (GenericsType genericsType : genericsTypes) { if (p.test(genericsType)) { return true; } } return false; } /** * Get the parameter and return types of the abstract method of SAM * * If the abstract method is not parameterized, we will get generics placeholders, e.g. T, U * For example, the abstract method of {@link java.util.function.Function} is * * R apply(T t); * * * We parameterize the above interface as {@code Function}, then the abstract method will be * * Integer apply(String t); * * * When we call {@code parameterizeSAM} on the ClassNode {@code Function}, * we can get parameter types and return type of the above abstract method, * i.e. ClassNode {@code ClassHelper.STRING_TYPE} and {@code ClassHelper.Integer_TYPE} * * @param sam the class node which contains only one abstract method * @return the parameter and return types * @since 3.0.0 * */ public static Tuple2 parameterizeSAM(ClassNode sam) { MethodNode methodNode = ClassHelper.findSAM(sam); final Map map = makeDeclaringAndActualGenericsTypeMapOfExactType(methodNode.getDeclaringClass(), sam); ClassNode[] parameterTypes = Arrays.stream(methodNode.getParameters()) .map(e -> { ClassNode originalParameterType = e.getType(); return originalParameterType.isGenericsPlaceHolder() ? findActualTypeByGenericsPlaceholderName(originalParameterType.getUnresolvedName(), map) : originalParameterType; }) .toArray(ClassNode[]::new); ClassNode originalReturnType = methodNode.getReturnType(); ClassNode returnType = originalReturnType.isGenericsPlaceHolder() ? findActualTypeByGenericsPlaceholderName(originalReturnType.getUnresolvedName(), map) : originalReturnType; return tuple(parameterTypes, returnType); } /** * Get the actual type according to the placeholder name * * @param placeholderName the placeholder name, e.g. T, E * @param genericsPlaceholderAndTypeMap the result of {@link #makeDeclaringAndActualGenericsTypeMap(ClassNode, ClassNode)} * @return the actual type */ public static ClassNode findActualTypeByGenericsPlaceholderName(String placeholderName, Map genericsPlaceholderAndTypeMap) { for (Map.Entry entry : genericsPlaceholderAndTypeMap.entrySet()) { GenericsType declaringGenericsType = entry.getKey(); if (placeholderName.equals(declaringGenericsType.getName())) { return entry.getValue().getType().redirect(); } } return null; } private static class ParameterizedTypeCacheKey { private ClassNode genericsClass; private ClassNode actualType; public ParameterizedTypeCacheKey(ClassNode genericsClass, ClassNode actualType) { this.genericsClass = genericsClass; this.actualType = actualType; } public ClassNode getGenericsClass() { return genericsClass; } public void setGenericsClass(ClassNode genericsClass) { this.genericsClass = genericsClass; } public ClassNode getActualType() { return actualType; } public void setActualType(ClassNode actualType) { this.actualType = actualType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParameterizedTypeCacheKey cacheKey = (ParameterizedTypeCacheKey) o; return genericsClass == cacheKey.genericsClass && actualType == cacheKey.actualType; } @Override public int hashCode() { return Objects.hash(genericsClass, actualType); } } } |
blob | long method, long method, long method | t | t | f | long method, long method, long method | blob | 0 | 6257 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java/#L68-L1044 | 1 | 626 | 6257 | critical |
| 584 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | long method | t | t | f | long method | blob | 0 | 5798 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 1 | 584 | 5798 | major |
| 162 | {"response": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BatchWriterReplicationReplayer implements AccumuloReplicationReplayer { private static final Logger log = LoggerFactory.getLogger(BatchWriterReplicationReplayer.class); @Override public long replicateLog(ClientContext context, String tableName, WalEdits data) throws RemoteReplicationException { final LogFileKey key = new LogFileKey(); final LogFileValue value = new LogFileValue(); final long memoryInBytes = context.getConfiguration() .getAsBytes(Property.TSERV_REPLICATION_BW_REPLAYER_MEMORY); BatchWriter bw = null; long mutationsApplied = 0L; try { for (ByteBuffer edit : data.getEdits()) { DataInputStream dis = new DataInputStream(ByteBufferUtil.toByteArrayInputStream(edit)); try { key.readFields(dis); // TODO this is brittle because AccumuloReplicaSystem isn't actually calling // LogFileValue.write, but we're expecting // what we receive to be readable by the LogFileValue. value.readFields(dis); } catch (IOException e) { log.error("Could not deserialize edit from stream", e); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_DESERIALIZE, "Could not deserialize edit from stream"); } // Create the batchScanner if we don't already have one. if (bw == null) { BatchWriterConfig bwConfig = new BatchWriterConfig(); bwConfig.setMaxMemory(memoryInBytes); try { bw = context.createBatchWriter(tableName, bwConfig); } catch (TableNotFoundException e) { throw new RemoteReplicationException(RemoteReplicationErrorCode.TABLE_DOES_NOT_EXIST, "Table " + tableName + " does not exist"); } } log.info("Applying {} mutations to table {} as part of batch", value.mutations.size(), tableName); // If we got a ServerMutation, we have to make sure that we preserve the systemTimestamp // otherwise // the local system will assign a new timestamp. List mutationsCopy = new ArrayList<>(value.mutations.size()); long mutationsCopied = 0L; for (Mutation orig : value.mutations) { if (orig instanceof ServerMutation) { mutationsCopied++; ServerMutation origServer = (ServerMutation) orig; Mutation copy = new Mutation(orig.getRow()); for (ColumnUpdate update : orig.getUpdates()) { long timestamp; // If the update doesn't have a timestamp, pull it from the ServerMutation if (!update.hasTimestamp()) { timestamp = origServer.getSystemTimestamp(); } else { timestamp = update.getTimestamp(); } // TODO ACCUMULO-2937 cache the CVs if (update.isDeleted()) { copy.putDelete(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp); } else { copy.put(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp, update.getValue()); } } // We also need to preserve the replicationSource information to prevent cycles Set replicationSources = orig.getReplicationSources(); if (replicationSources != null && !replicationSources.isEmpty()) { for (String replicationSource : replicationSources) { copy.addReplicationSource(replicationSource); } } mutationsCopy.add(copy); } else { mutationsCopy.add(orig); } } log.debug("Copied {} mutations to ensure server-assigned timestamps are propagated", mutationsCopied); try { bw.addMutations(mutationsCopy); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } log.debug("{} mutations added to the BatchScanner", mutationsCopy.size()); mutationsApplied += mutationsCopy.size(); } } finally { if (bw != null) { try { bw.close(); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } } } log.info("Applied {} mutations in total to {}", mutationsApplied, tableName); return mutationsApplied; } } |
blob | Not specified | f | f | f | false | 0 | 1995 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/tserver/src/main/java/org/apache/accumulo/tserver/replication/BatchWriterReplicationReplayer.java/#L50-L171 | 2 | 162 | 1995 | major | |
| 1632 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11512 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 1632 | 11512 | minor |
| 2414 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Primitive obsession, 6. Object orientation abuser, 7. Inappropriate intimacy, 8. Inappropriate comments, 9. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Primitive obsession, 6 Object orientation abuser, 7 Inappropriate intimacy, 8 Inappropriate comments, 9 Large class | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Primitive obsession, 6. Object orientation abuser, 7. Inappropriate intimacy, 8. Inappropriate comments, 9. Large class | data class | 0 | 14415 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 2414 | 14415 | minor |
| 221 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } } |
data class | true, "the bad smells are" | t | f | f | true, "the bad smells are" | data class | 0 | 2394 | https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 | 1 | 221 | 2394 | minor |
| 2289 | YES I found bad smells! The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13914 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 2289 | 13914 | minor |
| 243 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 2648 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 1 | 243 | 2648 | critical |
| 308 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RewriteLoadBalancerClient implements LoadBalancerClient { private static final Logger _log = LoggerFactory.getLogger(TrackerClient.class); private final String _serviceName; private final URI _uri; private final RewriteClient _client; public RewriteLoadBalancerClient(String serviceName, URI uri, TransportClient client) { _serviceName = serviceName; _uri = uri; _client = new RewriteClient(client, new D2URIRewriter(uri)); debug(_log, "created rewrite client: ", this); } @Override public void restRequest(RestRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.restRequest(request, requestContext, wireAttrs, callback); } @Override public void streamRequest(StreamRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.streamRequest(request, requestContext, wireAttrs, callback); } @Override public void shutdown(Callback callback) { _client.shutdown(callback); } @Deprecated public TransportClient getWrappedClient() { return _client; } public TransportClient getDecoratedClient() { return _client; } @Override public URI getUri() { return _uri; } public String getServiceName() { return _serviceName; } @Override public String toString() { return "RewriteLoadBalancerClient [_serviceName=" + _serviceName + ", _uri=" + _uri + ", _wrappedClient=" + _client + "]"; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3201 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/d2/src/main/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClient.java/#L41-L111 | 2 | 308 | 3201 | minor |
| 2409 | {"response": "YES I found bad smells the bad smells are: 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | 2. feature envy | t | t | f | 2. feature envy | blob | 0 | 14391 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 1 | 2409 | 14391 | major |
| 2056 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12950 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2056 | 12950 | major |
| 2269 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Tight coupling 5. Poor exception handling 6. Magic numbers/strings 7. Inconsistent naming conventions 8. Inefficient data type usage 9. Incomplete error handling 10. Use of global variables/constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | Long method2 Feature envy3 Duplicate code4 Tight coupling5 Poor exception handling6 Magic numbers/strings7 Inconsistent naming conventions8 Inefficient data type usage9 Incomplete error handling | t | f | f | . Long method2. Feature envy3. Duplicate code4. Tight coupling5. Poor exception handling6. Magic numbers/strings7. Inconsistent naming conventions8. Inefficient data type usage9. Incomplete error handling | blob | 0 | 13750 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 2 | 2269 | 13750 | major |
| 1908 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 12396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 1 | 1908 | 12396 | major |
| 939 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | long method, blob | t | t | f | long method, blob | data class | 0 | 8450 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 1 | 939 | 8450 | major |
| 1438 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10968 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 1438 | 10968 | minor |
| 5 | {"message": "YES I found bad smells. the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | Not specified | f | f | f | false | 0 | 565 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 2 | 5 | 565 | minor | |
| 4726 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DiscoverAnnotatedBeans implements DynamicDeployer { public AppModule deploy(AppModule appModule) throws OpenEJBException { for (EjbModule ejbModule : appModule.getEjbModules()) { ejbModule.initAppModule(appModule); setModule(ejbModule); try { deploy(ejbModule); } finally { removeModule(); } } for (ClientModule clientModule : appModule.getClientModules()) { clientModule.initAppModule(appModule); setModule(clientModule); try { deploy(clientModule); } finally { removeModule(); } } for (ConnectorModule connectorModule : appModule.getConnectorModules()) { connectorModule.initAppModule(appModule); setModule(connectorModule); try { deploy(connectorModule); } finally { removeModule(); } } for (WebModule webModule : appModule.getWebModules()) { webModule.initAppModule(appModule); setModule(webModule); try { deploy(webModule); } finally { removeModule(); } } final AdditionalBeanDiscoverer discoverer = SystemInstance.get().getComponent(AdditionalBeanDiscoverer.class); if (discoverer != null) { appModule = discoverer.discover(appModule); } return appModule; } public ClientModule deploy(ClientModule clientModule) throws OpenEJBException { if (clientModule.getApplicationClient() == null){ clientModule.setApplicationClient(new ApplicationClient()); } // Lots of jars have main classes so this might not even be an app client. // We're not going to scrape it for @LocalClient or @RemoteClient annotations // unless they flag us specifically by adding a META-INF/application-client.xml // // ClientModules that already have a AnnotationFinder have been generated automatically // from an EjbModule, so we don't skip those ever. if (clientModule.getFinder() == null && clientModule.getAltDDs().containsKey("application-client.xml")) if (clientModule.getApplicationClient() != null && clientModule.getApplicationClient().isMetadataComplete()) return clientModule; IAnnotationFinder finder = clientModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(clientModule); } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForClientModule.url", clientModule.getJarLocation()); return clientModule; } catch (Exception e) { startupLogger.warning("startup.scrapeFailedForClientModule", e, clientModule.getJarLocation()); return clientModule; } } // This method is also called by the deploy(EjbModule) method to see if those // modules have any @LocalClient or @RemoteClient classes for (Annotated> clazz : finder.findMetaAnnotatedClasses(LocalClient.class)) { clientModule.getLocalClients().add(clazz.get().getName()); } for (Annotated> clazz : finder.findMetaAnnotatedClasses(RemoteClient.class)) { clientModule.getRemoteClients().add(clazz.get().getName()); } if (clientModule.getApplicationClient() == null){ if (clientModule.getRemoteClients().size() > 0 || clientModule.getLocalClients().size() > 0) { clientModule.setApplicationClient(new ApplicationClient()); } } return clientModule; } public ConnectorModule deploy(ConnectorModule connectorModule) throws OpenEJBException { org.apache.openejb.jee.Connector connector = connectorModule.getConnector(); if (connector == null) { connector = new org.apache.openejb.jee.Connector(); } // JCA 1.6 - 18.3.1 do not look at annotations if the provided connector // deployment descriptor is "meta-data complete". float specVersion = 0; try { specVersion = Float.parseFloat(connector.getVersion()); } catch (Exception e) { } if (specVersion < 1.6 || Boolean.TRUE.equals(connector.isMetadataComplete())) { return connectorModule; } IAnnotationFinder finder = connectorModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(connectorModule); connectorModule.setFinder(finder); } catch (Exception e) { // TODO: some sort of error return connectorModule; } } List> connectorClasses = finder.findAnnotatedClasses(Connector.class); // are we allowed to have more than one connector class? Not without a deployment descriptor if (connector.getResourceAdapter() == null || connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { if (connectorClasses.size() == 0) { // fail some validation here too } if (connectorClasses.size() > 1) { // too many connector classes, this is against the spec // something like connectorModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); } } Class connectorClass = null; if (connectorClasses.size() == 1) { connectorClass = connectorClasses.get(0); } if (connectorClasses.size() > 1) { for (Class cls : connectorClasses) { if (cls.getName().equals(connector.getResourceAdapter().getResourceAdapterClass())) { connectorClass = cls; break; } } } if (connectorClass != null) { if (connector.getResourceAdapter() == null) { connector.setResourceAdapter(new ResourceAdapter()); } if (connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { connector.getResourceAdapter().setResourceAdapterClass(connectorClass.getName()); } Connector connectorAnnotation = connectorClass.getAnnotation(Connector.class); connector.setDisplayNames(getTexts(connector.getDisplayNames(), connectorAnnotation.displayName())); connector.setDescriptions(getTexts(connector.getDescriptions(), connectorAnnotation.description())); connector.setEisType(getString(connector.getEisType(), connectorAnnotation.eisType())); connector.setVendorName(getString(connector.getVendorName(), connectorAnnotation.vendorName())); connector.setResourceAdapterVersion(getString(connector.getResourceAdapterVersion(), connectorAnnotation.version())); if (connector.getIcons().isEmpty()) { int smallIcons = connectorAnnotation.smallIcon().length; int largeIcons = connectorAnnotation.largeIcon().length; for (int i = 0; i < smallIcons && i < largeIcons; i++) { Icon icon = new Icon(); // locale can't be specified in the annotation and it is en by default // so on other systems it doesn't work because Icon return the default locale icon.setLang(Locale.getDefault().getLanguage()); if (i < smallIcons) { icon.setSmallIcon(connectorAnnotation.smallIcon()[i]); } if (i < largeIcons) { icon.setLargeIcon(connectorAnnotation.largeIcon()[i]); } connector.getIcons().add(icon); } } if (connector.getLicense() == null) { License license = new License(); connector.setLicense(license); license.setLicenseRequired(connectorAnnotation.licenseRequired()); } connector.getLicense().setDescriptions(getTexts(connector.getLicense().getDescriptions(), connectorAnnotation.licenseDescription())); SecurityPermission[] annotationSecurityPermissions = connectorAnnotation.securityPermissions(); List securityPermission = connector.getResourceAdapter().getSecurityPermission(); if (securityPermission == null || securityPermission.size() == 0) { for (SecurityPermission sp : annotationSecurityPermissions) { org.apache.openejb.jee.SecurityPermission permission = new org.apache.openejb.jee.SecurityPermission(); permission.setSecurityPermissionSpec(sp.permissionSpec()); permission.setDescriptions(stringsToTexts(sp.description())); securityPermission.add(permission); } } Class[] annotationRequiredWorkContexts = connectorAnnotation.requiredWorkContexts(); List requiredWorkContext = connector.getRequiredWorkContext(); if (requiredWorkContext.size() == 0) { for (Class cls : annotationRequiredWorkContexts) { requiredWorkContext.add(cls.getName()); } } OutboundResourceAdapter outboundResourceAdapter = connector.getResourceAdapter().getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); connector.getResourceAdapter().setOutboundResourceAdapter(outboundResourceAdapter); } List authenticationMechanisms = outboundResourceAdapter.getAuthenticationMechanism(); javax.resource.spi.AuthenticationMechanism[] authMechanisms = connectorAnnotation.authMechanisms(); if (authenticationMechanisms.size() == 0) { for (javax.resource.spi.AuthenticationMechanism am : authMechanisms) { AuthenticationMechanism authMechanism = new AuthenticationMechanism(); authMechanism.setAuthenticationMechanismType(am.authMechanism()); authMechanism.setCredentialInterface(am.credentialInterface().toString()); authMechanism.setDescriptions(stringsToTexts(am.description())); authenticationMechanisms.add(authMechanism); } } if (outboundResourceAdapter.getTransactionSupport() == null) { outboundResourceAdapter.setTransactionSupport(TransactionSupportType.fromValue(connectorAnnotation.transactionSupport().toString())); } if (outboundResourceAdapter.isReauthenticationSupport() == null) { outboundResourceAdapter.setReauthenticationSupport(connectorAnnotation.reauthenticationSupport()); } } else { // we couldn't process a connector class - probably a validation issue which we should warn about. } // process @ConnectionDescription(s) List> classes = finder.findAnnotatedClasses(ConnectionDefinitions.class); for (Class cls : classes) { ConnectionDefinitions connectionDefinitionsAnnotation = cls.getAnnotation(ConnectionDefinitions.class); ConnectionDefinition[] definitions = connectionDefinitionsAnnotation.value(); for (ConnectionDefinition definition : definitions) { processConnectionDescription(connector.getResourceAdapter(), definition, cls); } } classes = finder.findAnnotatedClasses(ConnectionDefinition.class); for (Class cls : classes) { ConnectionDefinition connectionDefinitionAnnotation = cls.getAnnotation(ConnectionDefinition.class); processConnectionDescription(connector.getResourceAdapter(), connectionDefinitionAnnotation, cls); } InboundResourceadapter inboundResourceAdapter = connector.getResourceAdapter().getInboundResourceAdapter(); if (inboundResourceAdapter == null) { inboundResourceAdapter = new InboundResourceadapter(); connector.getResourceAdapter().setInboundResourceAdapter(inboundResourceAdapter); } MessageAdapter messageAdapter = inboundResourceAdapter.getMessageAdapter(); if (messageAdapter == null) { messageAdapter = new MessageAdapter(); inboundResourceAdapter.setMessageAdapter(messageAdapter); } classes = finder.findAnnotatedClasses(Activation.class); for (Class cls : classes) { MessageListener messageListener = null; Activation activationAnnotation = cls.getAnnotation(Activation.class); List messageListeners = messageAdapter.getMessageListener(); for (MessageListener ml : messageListeners) { if (cls.getName().equals(ml.getActivationSpec().getActivationSpecClass())) { messageListener = ml; break; } } if (messageListener == null) { Class[] listeners = activationAnnotation.messageListeners(); for (Class listener : listeners) { messageAdapter.addMessageListener(new MessageListener(listener.getName(), cls.getName())); } } } classes = finder.findAnnotatedClasses(AdministeredObject.class); List adminObjects = connector.getResourceAdapter().getAdminObject(); for (Class cls : classes) { AdministeredObject administeredObjectAnnotation = cls.getAnnotation(AdministeredObject.class); Class[] adminObjectInterfaces = administeredObjectAnnotation.adminObjectInterfaces(); AdminObject adminObject = null; for (AdminObject admObj : adminObjects) { if (admObj.getAdminObjectClass().equals(cls.getName())) { adminObject = admObj; } } if (adminObject == null) { for (Class iface : adminObjectInterfaces) { AdminObject newAdminObject = new AdminObject(); newAdminObject.setAdminObjectClass(cls.getName()); newAdminObject.setAdminObjectInterface(iface.getName()); adminObjects.add(newAdminObject); } } } // need to make a list of classes to process for config properties // resource adapter String raCls = connector.getResourceAdapter().getResourceAdapterClass(); process(connectorModule.getClassLoader(), raCls, connector.getResourceAdapter()); // managedconnectionfactory if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getOutboundResourceAdapter() != null) { List connectionDefinitions = connector.getResourceAdapter().getOutboundResourceAdapter().getConnectionDefinition(); for (org.apache.openejb.jee.ConnectionDefinition connectionDefinition : connectionDefinitions) { process(connectorModule.getClassLoader(), connectionDefinition.getManagedConnectionFactoryClass(), connectionDefinition); } } // administeredobject if (connector.getResourceAdapter() != null) { List raAdminObjects = connector.getResourceAdapter().getAdminObject(); for (AdminObject raAdminObject : raAdminObjects) { process(connectorModule.getClassLoader(), raAdminObject.getAdminObjectClass(), raAdminObject); } } // activationspec if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter() != null) { List messageListeners = connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter().getMessageListener(); for (MessageListener messageListener : messageListeners) { ActivationSpec activationSpec = messageListener.getActivationSpec(); process(connectorModule.getClassLoader(), activationSpec.getActivationSpecClass(), activationSpec); } } return connectorModule; } void process(ClassLoader cl, String cls, Object object) { List configProperties = null; try { // grab a list of ConfigProperty objects configProperties = (List) object.getClass().getDeclaredMethod("getConfigProperty").invoke(object); } catch (Exception e) { } if (configProperties == null) { // can't get config properties return; } ClassLoader classLoader = cl; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final List allowedTypes = Arrays.asList(new String[] { Boolean.class.getName(), String.class.getName(), Integer.class.getName(), Double.class.getName(), Byte.class.getName(), Short.class.getName(), Long.class.getName(), Float.class.getName(), Character.class.getName()}); try { Class clazz = classLoader.loadClass(realClassName(cls)); Object o = clazz.newInstance(); // add any introspected properties BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); Class type = propertyDescriptor.getPropertyType(); if (type == null) { continue; } if (type.isPrimitive()) { type = getWrapper(type.getName()); } if (! allowedTypes.contains(type.getName())) { continue; } if (! containsConfigProperty(configProperties, name)) { if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); Object value = null; try { value = propertyDescriptor.getReadMethod().invoke(o); } catch (Exception e) { } javax.resource.spi.ConfigProperty annotation = propertyDescriptor.getWriteMethod().getAnnotation(javax.resource.spi.ConfigProperty.class); if (annotation == null) { try { // if there's no annotation on the setter, we'll try and scrape one off the field itself (assuming the same name) annotation = clazz.getDeclaredField(name).getAnnotation(javax.resource.spi.ConfigProperty.class); } catch (Exception ignored) { // no-op : getDeclaredField() throws exceptions and does not return null } } configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(getConfigPropertyType(annotation, type)); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null && annotation.defaultValue().length() > 0) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); configProperty.setDescriptions(stringsToTexts(annotation.description())); } } } } // add any annotated fields we haven't already picked up Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { javax.resource.spi.ConfigProperty annotation = field.getAnnotation(javax.resource.spi.ConfigProperty.class); String name = field.getName(); Object value = null; try { value = field.get(o); } catch (Exception e) { } if (! containsConfigProperty(configProperties, name)) { String type = getConfigPropertyType(annotation, field.getType()); if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(type); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); } } } } } catch (Exception e) { e.printStackTrace(); } } private String getConfigPropertyType(javax.resource.spi.ConfigProperty annotation, Class type) { Class t = (annotation == null) ? null : annotation.type(); if (t == null && type != null) { return type.getName(); } else if (t == null) { return null; } if (t.equals(Object.class)) { t = type; } if (t == null) { // t == null && type == null return null; } if (t.isPrimitive()) { t = getWrapper(t.getName()); } return t.getName(); } private boolean containsConfigProperty(List configProperties, String name) { for (ConfigProperty configProperty : configProperties) { if (configProperty.getConfigPropertyName().equals(name)) { return true; } } return false; } private Class getWrapper(String primitiveType) { final Map> builtInMap = new HashMap>();{ builtInMap.put("int", Integer.class); builtInMap.put("long", Long.class); builtInMap.put("double", Double.class); builtInMap.put("float", Float.class); builtInMap.put("boolean", Boolean.class); builtInMap.put("char", Character.class); builtInMap.put("byte", Byte.class); builtInMap.put("void", Void.class); builtInMap.put("short", Short.class); } return builtInMap.get(primitiveType); } private void processConnectionDescription(ResourceAdapter resourceAdapter, ConnectionDefinition connectionDefinitionAnnotation, Class cls) { // try and find the managed connection factory OutboundResourceAdapter outboundResourceAdapter = resourceAdapter.getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); resourceAdapter.setOutboundResourceAdapter(outboundResourceAdapter); } List connectionDefinition = outboundResourceAdapter.getConnectionDefinition(); org.apache.openejb.jee.ConnectionDefinition definition = null; for (org.apache.openejb.jee.ConnectionDefinition cd : connectionDefinition) { if (cd.getManagedConnectionFactoryClass().equals(cls.getName())) { definition = cd; break; } } if (definition == null) { definition = new org.apache.openejb.jee.ConnectionDefinition(); outboundResourceAdapter.getConnectionDefinition().add(definition); } if (definition.getManagedConnectionFactoryClass() == null) { definition.setManagedConnectionFactoryClass(cls.getName()); } if (definition.getConnectionInterface() == null) { definition.setConnectionInterface(connectionDefinitionAnnotation.connection().getName()); } if (definition.getConnectionImplClass() == null) { definition.setConnectionImplClass(connectionDefinitionAnnotation.connectionImpl().getName()); } if (definition.getConnectionFactoryInterface() == null) { definition.setConnectionFactoryInterface(connectionDefinitionAnnotation.connectionFactory().getName()); } if (definition.getConnectionFactoryImplClass() == null) { definition.setConnectionFactoryImplClass(connectionDefinitionAnnotation.connectionFactoryImpl().getName()); } } private Text[] stringsToTexts(String[] strings) { if (strings == null) { return null; } Text[] result = new Text[strings.length]; for (int i = 0; i < result.length; i++) { result[i] = new Text(); result[i].setValue(strings[i]); } return result; } private String getString(String descriptorString, String annotationString) { if (descriptorString != null && descriptorString.length() > 0) { return descriptorString; } if (annotationString != null && annotationString.length() > 0) { return annotationString; } return null; } private Text[] getTexts(Text[] originalTexts, String[] newStrings) { if (newStrings != null && newStrings.length > 0 && (originalTexts == null || originalTexts.length == 0)) { Text[] texts = new Text[newStrings.length]; for (int i = 0; i < newStrings.length; i++) { texts[i] = new Text(null, newStrings[i]); } return texts; } else { return originalTexts; } } public WebModule deploy(WebModule webModule) throws OpenEJBException { WebApp webApp = webModule.getWebApp(); if (webApp != null && (webApp.isMetadataComplete())) return webModule; try { if (webModule.getFinder() == null) { webModule.setFinder(FinderFactory.createFinder(webModule)); } } catch (Exception e) { startupLogger.warning("Unable to scrape for @WebService or @WebServiceProvider annotations. AnnotationFinder failed.", e); return webModule; } if (webApp == null) { webApp = new WebApp(); webModule.setWebApp(webApp); } List existingServlets = new ArrayList(); for (Servlet servlet : webApp.getServlet()) { if (servlet.getServletClass() != null) { existingServlets.add(servlet.getServletClass()); } } IAnnotationFinder finder = webModule.getFinder(); List classes = new ArrayList(); classes.addAll(finder.findAnnotatedClasses(WebService.class)); classes.addAll(finder.findAnnotatedClasses(WebServiceProvider.class)); for (Class webServiceClass : classes) { // If this class is also annotated @Stateless or @Singleton, we should skip it if (webServiceClass.isAnnotationPresent(Singleton.class) || webServiceClass.isAnnotationPresent(Stateless.class)) { webModule.getEjbWebServices().add(webServiceClass.getName()); continue; } int modifiers = webServiceClass.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || isAbstract(modifiers)) { continue; } if (existingServlets.contains(webServiceClass.getName())) continue; // create webApp and webservices objects if they don't exist already // add new element Servlet servlet = new Servlet(); servlet.setServletName(webServiceClass.getName()); servlet.setServletClass(webServiceClass.getName()); webApp.getServlet().add(servlet); } /* * REST */ // get by annotations webModule.getRestClasses().addAll(findRestClasses(webModule, finder)); addJaxRsProviders(finder, webModule.getJaxrsProviders(), Provider.class); // Applications with a default constructor // findSubclasses will not work by default to gain a lot of time // look FinderFactory for the flag to activate it or // use @ApplicationPath("/") List> applications = finder.findSubclasses(Application.class); for (Class app : applications) { addRestApplicationIfPossible(webModule, app); } // look for ApplicationPath, it will often return the same than the previous one // but without finder.link() invocation it still works // so it can save a lot of startup time List>> applicationsByAnnotation = finder.findMetaAnnotatedClasses(ApplicationPath.class); for (Annotated> annotatedApp : applicationsByAnnotation) { final Class app = annotatedApp.get(); if (!Application.class.isAssignableFrom(app)) { logger.error("class '" + app.getName() + "' is annotated with @ApplicationPath but doesn't implement " + Application.class.getName()); continue; } addRestApplicationIfPossible(webModule, (Class) app); } /* * JSF */ final ClassLoader classLoader = webModule.getClassLoader(); for (String jsfClass : JSF_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(jsfClass); } catch (ClassNotFoundException e) { continue; } final List>> found = finder.findMetaAnnotatedClasses(clazz); final Set convertedClasses = new HashSet(found.size()); for (Annotated> annotated : found) { convertedClasses.add(annotated.get().getName()); } webModule.getJsfAnnotatedClasses().put(jsfClass, convertedClasses); } /* * Servlet, Filter, Listener */ Map urlByClasses = null; for (String apiClassName : WEB_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(apiClassName); } catch (ClassNotFoundException e) { continue; } if (urlByClasses == null) { // try to reuse scanning info, maybe some better indexing can be a nice idea if (finder instanceof FinderFactory.ModuleLimitedFinder) { final IAnnotationFinder limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (limitedFinder instanceof AnnotationFinder) { final Archive archive = ((AnnotationFinder) limitedFinder).getArchive(); if (archive instanceof WebappAggregatedArchive) { final Map> index = ((WebappAggregatedArchive) archive).getClassesMap(); urlByClasses = new HashMap(); for (Map.Entry> entry : index.entrySet()) { final String url = entry.getKey().toExternalForm(); for (String current : entry.getValue()) { urlByClasses.put(current, url); } } } } } } final List>> found = finder.findMetaAnnotatedClasses(clazz); addWebAnnotatedClassInfo(urlByClasses, webModule.getWebAnnotatedClasses(), found); } if (urlByClasses != null) { urlByClasses.clear(); } return webModule; } private void addJaxRsProviders(final IAnnotationFinder finder, final Collection set, final Class annotation) { for (Annotated> provider : finder.findMetaAnnotatedClasses(annotation)) { set.add(provider.get().getName()); } } private static void addRestApplicationIfPossible(final WebModule webModule, final Class app) { if (app.getConstructors().length == 0) { webModule.getRestApplications().add(app.getName()); } else { for (Constructor ctr : app.getConstructors()) { if (ctr.getParameterTypes().length == 0) { webModule.getRestApplications().add(app.getName()); break; } } } } public EjbModule deploy(EjbModule ejbModule) throws OpenEJBException { if (ejbModule.getEjbJar() != null && ejbModule.getEjbJar().isMetadataComplete()) return ejbModule; try { if (ejbModule.getFinder() == null) { ejbModule.setFinder(FinderFactory.createFinder(ejbModule)); } } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForModule", ejbModule.getJarLocation()); return ejbModule; } catch (Exception e) { startupLogger.warning("Unable to scrape for @Stateful, @Stateless, @Singleton or @MessageDriven annotations. AnnotationFinder failed.", e); return ejbModule; } IAnnotationFinder finder = ejbModule.getFinder(); final List managedClasses; { final Beans beans = ejbModule.getBeans(); if (beans != null) { managedClasses = beans.getManagedClasses(); final List classNames = getBeanClasses(finder); for (String rawClassName : classNames) { final String className = realClassName(rawClassName); try { final ClassLoader loader = ejbModule.getClassLoader(); final Class clazz = loader.loadClass(className); // The following can NOT be beans in CDI // 1. Non-static inner classes if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) continue; // // // 2. Abstract classes (unless they are an @Decorator) // if (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isAnnotationPresent(javax.decorator.Decorator.class)) continue; // // 3. Implementations of Extension if (Extension.class.isAssignableFrom(clazz)) continue; managedClasses.add(className); } catch (ClassNotFoundException e) { // todo log debug warning } catch (java.lang.NoClassDefFoundError e) { // no-op } } // passing jar location to be able to manage maven classes/test-classes which have the same moduleId String id = ejbModule.getModuleId(); if (ejbModule.getJarLocation() != null && ejbModule.getJarLocation().contains(ejbModule.getModuleId() + "/target/test-classes".replace("/", File.separator))) { // with maven if both src/main/java and src/test/java are deployed // moduleId.Comp exists twice so it fails // here we simply modify the test comp bean name to avoid it id += "_test"; } final String name = BeanContext.Comp.openejbCompName(id); final org.apache.openejb.jee.ManagedBean managedBean = new CompManagedBean(name, BeanContext.Comp.class); managedBean.setTransactionType(TransactionType.BEAN); ejbModule.getEjbJar().addEnterpriseBean(managedBean); } else { managedClasses = new ArrayList(); } } final Set> specializingClasses = new HashSet>(); // Fill in default sessionType for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (!(bean instanceof SessionBean)) continue; SessionBean sessionBean = (SessionBean) bean; if (sessionBean.getSessionType() != null) continue; try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); sessionBean.setSessionType(getSessionType(clazz)); } catch (Throwable handledInValidation) { // no-op } } // Fill in default ejbName for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (bean.getEjbClass() == null) continue; if (bean.getEjbName() == null || bean.getEjbName().startsWith("@NULL@")) { ejbModule.getEjbJar().removeEnterpriseBean(bean.getEjbName()); try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); final String ejbName = getEjbName(bean, clazz); bean.setEjbName(ejbName); } catch (Throwable handledInValidation) { } ejbModule.getEjbJar().addEnterpriseBean(bean); } } /* 19.2: ejb-name: Default is the unqualified name of the bean class */ EjbJar ejbJar = ejbModule.getEjbJar(); for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Singleton.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Singleton singleton = beanClass.getAnnotation(Singleton.class); String ejbName = getEjbName(singleton, beanClass.get()); if (!isValidEjbAnnotationUsage(Singleton.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new SingletonBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.SINGLETON); if (singleton.mappedName() != null) { sessionBean.setMappedName(singleton.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateless.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateless stateless = beanClass.getAnnotation(Stateless.class); String ejbName = getEjbName(stateless, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateless.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatelessBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.STATELESS); if (stateless.mappedName() != null) { sessionBean.setMappedName(stateless.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } // The Specialization code is good, but it possibly needs to be moved to after the full processing of the bean // the plus is that it would get the required interfaces. The minus is that it would get all the other items // Possibly study alternatives. Alternatives might have different meta data completely while it seems Specializing beans inherit all meta-data // Anyway.. the qualifiers aren't getting inherited, so we need to fix that for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateful.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateful stateful = beanClass.getAnnotation(Stateful.class); String ejbName = getEjbName(stateful, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateful.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatefulBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; // TODO: We might be stepping on an xml override here sessionBean.setSessionType(SessionType.STATEFUL); if (stateful.mappedName() != null) { sessionBean.setMappedName(stateful.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(ManagedBean.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } ManagedBean managed = beanClass.getAnnotation(ManagedBean.class); String ejbName = getEjbName(managed, beanClass.get()); // TODO: this is actually against the spec, but the requirement is rather silly // (allowing @Stateful and @ManagedBean on the same class) // If the TCK doesn't complain we should discourage it if (!isValidEjbAnnotationUsage(ManagedBean.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new org.apache.openejb.jee.ManagedBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.MANAGED); final TransactionType transactionType = sessionBean.getTransactionType(); if (transactionType == null) sessionBean.setTransactionType(TransactionType.BEAN); } } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(MessageDriven.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } MessageDriven mdb = beanClass.getAnnotation(MessageDriven.class); String ejbName = getEjbName(mdb, beanClass.get()); if (!isValidEjbAnnotationUsage(MessageDriven.class, beanClass, ejbName, ejbModule)) continue; MessageDrivenBean messageBean = (MessageDrivenBean) ejbJar.getEnterpriseBean(ejbName); if (messageBean == null) { messageBean = new MessageDrivenBean(ejbName); ejbJar.addEnterpriseBean(messageBean); } if (messageBean.getEjbClass() == null) { messageBean.setEjbClass(beanClass.get()); } LegacyProcessor.process(beanClass.get(), messageBean); } for (Class specializingClass : sortClassesParentFirst(new ArrayList>(specializingClasses))) { final Class parent = specializingClass.getSuperclass(); if (parent == null || parent.equals(Object.class)) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsNothing", specializingClass.getName()); } boolean found = false; for (EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) { final String ejbClass = enterpriseBean.getEjbClass(); if (ejbClass != null && ejbClass.equals(parent.getName())) { managedClasses.remove(ejbClass); enterpriseBean.setEjbClass(specializingClass.getName()); found = true; } } if (!found) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsSimpleBean", specializingClass.getName()); } } AssemblyDescriptor assemblyDescriptor = ejbModule.getEjbJar().getAssemblyDescriptor(); if (assemblyDescriptor == null) { assemblyDescriptor = new AssemblyDescriptor(); ejbModule.getEjbJar().setAssemblyDescriptor(assemblyDescriptor); } startupLogger.debug("Searching for annotated application exceptions (see OPENEJB-980)"); List> appExceptions = finder.findAnnotatedClasses(ApplicationException.class); for (Class exceptionClass : appExceptions) { startupLogger.debug("...handling " + exceptionClass); ApplicationException annotation = exceptionClass.getAnnotation(ApplicationException.class); if (assemblyDescriptor.getApplicationException(exceptionClass) == null) { startupLogger.debug("...adding " + exceptionClass + " with rollback=" + annotation.rollback()); assemblyDescriptor.addApplicationException(exceptionClass, annotation.rollback(), annotation.inherited()); } else { mergeApplicationExceptionAnnotation(assemblyDescriptor, exceptionClass, annotation); } } // ejb can be rest bean and only then in standalone so scan providers here too // adding them to app since they should be in the app classloader if (ejbModule.getAppModule() != null) { addJaxRsProviders(finder, ejbModule.getAppModule().getJaxRsProviders(), Provider.class); } if (ejbModule.getAppModule() != null) { for (PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) { for (org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) { if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses()) && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) { final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE); // no need of meta currently since JPA providers doesn't support it final List> classes = new ArrayList>(); classes.addAll(finder.findAnnotatedClasses(Entity.class)); classes.addAll(finder.findAnnotatedClasses(Embeddable.class)); classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class)); final List existingClasses = pu.getClazz(); for (Class clazz : classes) { final String name = clazz.getName(); if ((packageName == null || name.startsWith(packageName)) && !existingClasses.contains(name)) { pu.getClazz().add(name); } } pu.setScanned(true); } } } } return ejbModule; } private SessionType getSessionType(Class clazz) { if (clazz.isAnnotationPresent(Stateful.class)) return SessionType.STATEFUL; if (clazz.isAnnotationPresent(Stateless.class)) return SessionType.STATELESS; if (clazz.isAnnotationPresent(Singleton.class)) return SessionType.SINGLETON; if (clazz.isAnnotationPresent(ManagedBean.class)) return SessionType.MANAGED; return null; } private String getEjbName(EnterpriseBean bean, Class clazz) { if (bean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) bean; switch (sessionBean.getSessionType()) { case STATEFUL: { final Stateful annotation = clazz.getAnnotation(Stateful.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case STATELESS: { final Stateless annotation = clazz.getAnnotation(Stateless.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case SINGLETON: { final Singleton annotation = clazz.getAnnotation(Singleton.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } } } if (bean instanceof MessageDrivenBean) { final MessageDriven annotation = clazz.getAnnotation(MessageDriven.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } return clazz.getSimpleName(); } private static boolean specified(final String name) { return name != null && name.length() != 0; } private List getBeanClasses(IAnnotationFinder finder) { // What we're hoping in this method is to get lucky and find // that our 'finder' instances is an AnnotationFinder that is // holding an AggregatedArchive so we can get the classes that // that pertain to each URL for CDI purposes. // // If not we call finder.getAnnotatedClassNames() which may return // more classes than actually apply to CDI. This can "pollute" // the CDI class space and break injection points if (!(finder instanceof FinderFactory.ModuleLimitedFinder)) return finder.getAnnotatedClassNames(); final IAnnotationFinder delegate = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (!(delegate instanceof AnnotationFinder)) return finder.getAnnotatedClassNames(); final AnnotationFinder annotationFinder = (AnnotationFinder) delegate; final Archive archive = annotationFinder.getArchive(); if (!(archive instanceof WebappAggregatedArchive)) return finder.getAnnotatedClassNames(); final List classes = new ArrayList(); final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive; final Map> map = aggregatedArchive.getClassesMap(); for (Map.Entry> entry : map.entrySet()) { if (hasBeansXml(entry.getKey())) classes.addAll(entry.getValue()); } return classes; } public static boolean hasBeansXml(URL url) { if (url.getPath().endsWith("WEB-INF/classes/")) return true; if (url.getPath().endsWith("!/META-INF/beans.xml")) return true; try { final URLClassLoader loader = new URLClassLoader(new URL[]{ url } , new EmptyResourcesClassLoader()); String[] paths = { "META-INF/beans.xml", "WEB-INF/beans.xml", "/WEB-INF/beans.xml", "/META-INF/beans.xml", }; for (String path : paths) { if (loader.findResource(path) != null) return true; } } catch (Exception e) { } return false; } private String getEjbName(MessageDriven mdb, Class beanClass) { return (mdb.name().isEmpty() ? beanClass.getSimpleName() : mdb.name()); } private String getEjbName(Stateful stateful, Class beanClass) { return (stateful.name().isEmpty() ? beanClass.getSimpleName() : stateful.name()); } private String getEjbName(Stateless stateless, Class beanClass) { return (stateless.name().isEmpty() ? beanClass.getSimpleName() : stateless.name()); } private String getEjbName(Singleton singleton, Class beanClass) { return (singleton.name().isEmpty() ? beanClass.getSimpleName() : singleton.name()); } private String getEjbName(ManagedBean managed, Class beanClass) { return (managed.value().isEmpty() ? beanClass.getSimpleName() : managed.value()); } private boolean isValidEjbAnnotationUsage(Class annotationClass, Annotated> beanClass, String ejbName, EjbModule ejbModule) { List> annotations = new ArrayList(asList(Singleton.class, Stateless.class, Stateful.class, MessageDriven.class)); annotations.remove(annotationClass); boolean b = true; for (Class secondAnnotation : annotations) { Annotation annotation = beanClass.getAnnotation(secondAnnotation); if (annotation == null) continue; String secondEjbName = null; if (annotation instanceof Stateful) { secondEjbName = getEjbName((Stateful) annotation, beanClass.get()); } else if (annotation instanceof Stateless) { secondEjbName = getEjbName((Stateless) annotation, beanClass.get()); } else if (annotation instanceof Singleton) { secondEjbName = getEjbName((Singleton) annotation, beanClass.get()); } else if (annotation instanceof MessageDriven) { secondEjbName = getEjbName((MessageDriven) annotation, beanClass.get()); } if (ejbName.equals(secondEjbName)) { ejbModule.getValidation().fail(ejbName, "multiplyAnnotatedAsBean", annotationClass.getSimpleName(), secondAnnotation.getSimpleName(), ejbName, beanClass.get().getName()); } } // not a dynamic proxy implemented bean if (beanClass.getAnnotation(PersistenceContext.class) == null && beanClass.getAnnotation(Proxy.class) == null && beanClass.get().isInterface()) { ejbModule.getValidation().fail(ejbName, "interfaceAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } if (!beanClass.get().isInterface() && isAbstract(beanClass.get().getModifiers())) { ejbModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } return b; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12693 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/config/AnnotationDeployer.java/#L411-L1700 | 2 | 4726 | 12693 | critical |
| 771 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7278 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 771 | 7278 | minor |
| 1788 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } } |
blob | 1 Long Method, 2 Data Class | t | f | f | 1. Long Method, 2. Data Class | blob | 0 | 11983 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 | 1 | 1788 | 11983 | major |
| 1330 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 10710 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 1 | 1330 | 10710 | minor |
| 137 | {"message": "YES I found bad smells", "bad smells are:": "1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1730 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 137 | 1730 | major |
| 2596 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 15008 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 | 2 | 2596 | 15008 | major |
| 303 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } |
feature envy | Long method | t | f | f | .Long method | feature envy | 0 | 3173 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 | 2 | 303 | 3173 | major |
| 2620 | {"message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | long method | t | t | f | long method | data class | 0 | 15054 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 2620 | 15054 | minor |
| 2705 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | data class, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method | t | t | f | data class, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method | blob | 0 | 15343 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 1 | 2705 | 15343 | minor |
| 1807 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WireAdminImpl implements WireAdmin, ServiceListener { private BundleContext m_bundleContext; // A Map containing a service reference associated to a producer and a List // of wire objects private Map m_consumers = new HashMap(); /* ServiceReferences, List */ private Map m_producers = new HashMap(); /* ServiceReferences, List */ private List m_wires; // List containing the wires //private BindingController wireAdminListenersBindingController; // Filter corresponding to a consumer service private Filter m_consumerFilter; // Filter corresponding to a producer service private Filter m_producerFilter; // EventManager private EventManager m_eventManager; private static int m_wireCount = 0; private AsyncMethodCaller m_asyncMethodCaller = new AsyncMethodCaller(); //m_eventDispatcher.stop(); private static PrintStream m_traceout = null; private static PrintStream m_errorout = System.err; /** * Constructor with package visibility * * @param bundleContext the bundle context */ WireAdminImpl(BundleContext bundleContext) { m_bundleContext = bundleContext; if(bundleContext.getProperty("fr.imag.adele.wireadmin.trace") != null) { String value = bundleContext.getProperty("fr.imag.adele.wireadmin.trace"); if(value.equals("true")) { m_traceout = System.out; } } // Create the event manager (the event manager will start its own thread) m_eventManager = new EventManager(m_bundleContext); try { m_producerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Producer)"); m_consumerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Consumer)"); } catch (InvalidSyntaxException e) { // never thrown since LDAP expressions are correct } // Recover persistent wires getPersistentWires(); // Activate thread that does asynchronous calls to // the producersConnected and consummersConnected methods new Thread(m_asyncMethodCaller).start(); // Gets all producers and consumers that are present at the // moment the wire admin is created try { // Registration for events must be done first, as some service // can be registered during initialization m_bundleContext.addServiceListener(this,"(|"+m_producerFilter.toString()+m_consumerFilter.toString()+")"); // Replacement for the two following lines which work under OSCAR, // but not work under IBM's SMF //m_bundleContext.addServiceListener(this,m_consumerFilter.toString()); //m_bundleContext.addServiceListener(this,m_producerFilter.toString()); // Get all producers ServiceReference[] producerRefs = m_bundleContext.getServiceReferences(Producer.class.getName(),null); if(producerRefs!=null) { // lock the producers Map to avoid concurrent modifications due // to service events synchronized(m_producers) { for(int i=0;iWire object that connects a Producer * service to a Consumer service. * * The Producer service and Consumer service do not * have to be registered when the Wire object is created. * * The Wire configuration data must be persistently stored. * All Wire connections are reestablished when the * WireAdmin service is registered. * A Wire can be permanently removed by using the * {@link #deleteWire} method. * * The Wire object's properties must have case * insensitive String objects as keys (like the Framework). * However, the case of the key must be preserved. * The type of the value of the property must be one of the following: * * * type = basetype * | vector | arrays * * basetype = String | Integer | Long * | Float | Double | Byte * | Short | Character * | Boolean * * primitive = long | int | short * | char | byte | double | float * * arrays = primitive '[]' | basetype '[]' * * vector = Vector of basetype * * * The WireAdmin service must automatically add the * following Wire properties: * * * {@link WireConstants#WIREADMIN_PID} set to the value of the Wire object's * persistent identity (PID). This value is generated by the * Wire Admin service when a Wire object is created. * * * {@link WireConstants#WIREADMIN_PRODUCER_PID} set to the value of * Producer service's PID. * * * {@link WireConstants#WIREADMIN_CONSUMER_PID} set to the value of * Consumer service's PID. * * * If the properties argument * already contains any of these keys, then the supplied values * are replaced with the values assigned by the Wire Admin service. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_CREATED} * after the new Wire object becomes available from {@link #getWires}. * * @param producerPID The service.pid of the Producer service * to be connected to the Wire object. * @param consumerPID The service.pid of the Consumer service * to be connected to the Wire object. * @param properties The Wire object's properties. This argument may be null * if the caller does not wish to define any Wire object's properties. * @return The Wire object for this connection. * @throws java.lang.IllegalArgumentException If * properties contains case variants of the same key name. */ public Wire createWire(String producerPID, String consumerPID, Dictionary props) { ServiceReference producerServiceRef = null; ServiceReference consumerServiceRef = null; Dictionary properties; if(props == null) { properties = new Hashtable(); } else { //Clone the dictionary properties = cloneProperties(props); } // Addition of mandatory properties properties.put(WireConstants.WIREADMIN_CONSUMER_PID, consumerPID); properties.put(WireConstants.WIREADMIN_PRODUCER_PID, producerPID); properties.put(WireConstants.WIREADMIN_PID, generateWirePID()); // p.327 "Wire objects can be created when the producer or consumer // service is not registered WireImpl wire = new WireImpl(producerPID, consumerPID, properties); // Initialize the wire wire.initialize(m_bundleContext,m_eventManager); // Add the wire to the list synchronized(m_wires) { m_wires.add(wire); } // p. 357 "The Wire Admin service must broadcast a WireAdminEvent of // type WireAdminEvent.WIRE_CREATED after the new Wire object becomes // available from getWires(java.lang.String)." m_eventManager.fireEvent(WireAdminEvent.WIRE_CREATED,wire); synchronized (m_producers) { Iterator producerIterator = m_producers.keySet().iterator(); while(producerIterator.hasNext()) { producerServiceRef = (ServiceReference) producerIterator.next(); if (producerServiceRef.getProperty(Constants.SERVICE_PID).equals(producerPID)) { wire.bindProducer(producerServiceRef); break; } } } synchronized (m_consumers) { Iterator consumerIterator = m_consumers.keySet().iterator(); while(consumerIterator.hasNext()) { consumerServiceRef = (ServiceReference) consumerIterator.next(); if (consumerServiceRef.getProperty(Constants.SERVICE_PID).equals(consumerPID)) { wire.bindConsumer(consumerServiceRef); break; } } } // p.327 If both Producer and Consumer services are registered, they are // connected by the wire admin service. if(wire.isConnected()) { List wires = (List) m_producers.get(producerServiceRef); wires.add(wire); m_asyncMethodCaller.consumersConnected(wire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(consumerServiceRef); wires.add(wire); m_asyncMethodCaller.producersConnected(wire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // Newly created wires are immediately persisted to avoid information // loss in case of crashes. (spec not clear about this) persistWires(); return wire; } /** * Delete a Wire object. * * The Wire object representing a connection between * a Producer service and a Consumer service must be * removed. * The persistently stored configuration data for the Wire object * must destroyed. The Wire object's method {@link Wire#isValid} will return false * after it is deleted. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_DELETED} * after the Wire object becomes invalid. * * @param wire The Wire object which is to be deleted. */ public void deleteWire(Wire wire) { if(m_wires.contains(wire)) { WireImpl wireImpl = (WireImpl) wire; m_wires.remove(wire); if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } wireImpl.invalidate(); // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_DELETED,wireImpl); // Persist state to avoid losses in case of crashes (spec not clear about this). persistWires(); } else { traceln("WireAdminImpl: Cannot delete a wire that is not managed by this service"); } } /** * Update the properties of a Wire object. * * The persistently stored configuration data for the Wire object * is updated with the new properties and then the Consumer and Producer * services will be called at the respective {@link Consumer#producersConnected} * and {@link Producer#consumersConnected} methods. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_UPDATED} * after the updated properties are available from the Wire object. * * @param wire The Wire object which is to be updated. * @param properties The new Wire object's properties or null if no properties are required. */ public void updateWire(Wire wire, Dictionary props) { if(m_wires.contains(wire) == false) { traceln("WireAdminImpl: Cannot update a wire that is not managed by this service"); return; } // Clone the dictionary Dictionary properties = cloneProperties(props); // Put again the mandatory properties, in case they are not set properties.put(WireConstants.WIREADMIN_CONSUMER_PID,wire.getProperties().get(WireConstants.WIREADMIN_CONSUMER_PID)); properties.put(WireConstants.WIREADMIN_PRODUCER_PID,wire.getProperties().get(WireConstants.WIREADMIN_PRODUCER_PID)); properties.put(WireConstants.WIREADMIN_PID,wire.getProperties().get(WireConstants.WIREADMIN_PID)); WireImpl wireImpl = (WireImpl) wire; wireImpl.updateProperties(properties); // Call methods on Consumer and Producer if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_UPDATED,wireImpl); } /** * Return the Wire objects that match the given filter. * * The list of available Wire objects is matched against the * specified filter. Wire objects which match the * filter must be returned. These Wire objects are not necessarily * connected. The Wire Admin service should not return * invalid Wire objects, but it is possible that a Wire * object is deleted after it was placed in the list. * * The filter matches against the Wire object's properties including * {@link WireConstants#WIREADMIN_PRODUCER_PID}, {@link WireConstants#WIREADMIN_CONSUMER_PID} * and {@link WireConstants#WIREADMIN_PID}. * * @param filter Filter string to select Wire objects * or null to select all Wire objects. * @return An array of Wire objects which match the filter * or null if no Wire objects match the filter. * @throws org.osgi.framework.InvalidSyntaxException If the specified filter * has an invalid syntax. * @see org.osgi.framework.Filter */ public Wire[] getWires(String filter) throws InvalidSyntaxException { List res = null; if (filter == null) { return (Wire [])m_wires.toArray(new Wire[m_wires.size()]); } else { Filter tempFilter = m_bundleContext.createFilter(filter); Iterator iter = m_wires.iterator(); while (iter.hasNext()) { WireImpl currentWire = (WireImpl) iter.next(); if (tempFilter.match(currentWire.getProperties())) { if (res == null) { res = new ArrayList(); } res.add(currentWire); } } } if (res == null) { return null; } else { return (Wire [])res.toArray(new Wire[res.size()]); } } /** * listens Producer and Consumer services changes * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent) */ public void serviceChanged(ServiceEvent e) { ServiceReference serviceRef = e.getServiceReference(); // A consumer service changed if (m_consumerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("consumer registered"); List wires = new ArrayList(); synchronized(m_consumers) { m_consumers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived consumer currentWire.bindConsumer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.add(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } } } if(!called) { // P. 329 "If the Consumer service has no Wire objects attached when it // is registered, the WireAdmin service must always call producersConnected(null) m_asyncMethodCaller.producersConnected((Consumer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("consumer unregistering"); synchronized(m_consumers) { m_consumers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindConsumer(); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.remove(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } else { currentWire.unbindConsumer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to consumer service modification traceln("consumer service modified"); break; } } // Removed else to manage services which are both producers AND consumers if (m_producerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("producer registered"); List wires = new ArrayList(); synchronized(m_producers) { m_producers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived producer currentWire.bindProducer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.add(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } } } if(!called) { // P. 329 "If the Producer service has no Wire objects attached when it // is registered, the WireAdmin service must always call consumersConnected(null) m_asyncMethodCaller.consumersConnected((Producer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("Producer unregistering"); synchronized(m_producers) { m_producers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindProducer(); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.remove(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } else { currentWire.unbindProducer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to producer service modification traceln("producer service modified"); break; } } } /** * release all references before stop */ synchronized void releaseAll() { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.invalidate(); } Iterator producerIt = m_producers.keySet().iterator(); while (producerIt.hasNext()) { ServiceReference producerRef = (ServiceReference) producerIt.next(); ((Producer)m_bundleContext.getService(producerRef)).consumersConnected(null); } Iterator consumerIt = m_consumers.keySet().iterator(); while (consumerIt.hasNext()) { ServiceReference consumerRef = (ServiceReference) consumerIt.next(); ((Consumer)m_bundleContext.getService(consumerRef)).producersConnected(null); } // Stop the thread m_asyncMethodCaller.stop(); // Notify the event manager so that it stops its thread m_eventManager.stop(); persistWires(); } /** * This method generates a PID. The pid is generated from the bundle id, * a hash code from the current time and a counter. * * @return a wire PID */ private String generateWirePID() { Date d = new Date(); String PID="wire."+m_bundleContext.getBundle().getBundleId()+d.hashCode()+m_wireCount; m_wireCount ++; // Maybe the counter should go above 9? if(m_wireCount>9) { m_wireCount = 0; } return PID; } /** * Recover persistent wires * */ private void getPersistentWires() { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(m_bundleContext.getDataFile("wires.ser"))); m_wires = (ArrayList) ois.readObject(); ois.close(); if(m_wires!=null) { traceln("Deserialized "+m_wires.size()+" wires"); Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.initialize(m_bundleContext,m_eventManager); } } else { traceln("Couldn't Deserialize wires"); m_wires = new ArrayList(); } } catch(FileNotFoundException ex) { // do not show anything as this exception is thrown every // time the wire admin service is launched for the first // time m_wires = new ArrayList(); } catch(Exception ex) { trace(ex); m_wires = new ArrayList(); } } /** * Persist existing wires * */ private void persistWires() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(m_bundleContext.getDataFile("wires.ser"))); oos.writeObject(m_wires); oos.close(); traceln("Serialized "+m_wires.size()+" wires"); } catch(Exception ex) { trace(ex); } } /** * print an error * @param message message to error */ static void error(String message) { if (m_errorout != null) { m_errorout.println(message); } } /** * print a trace * @param message message to trace */ static void traceln(String message) { if (m_traceout != null) { trace(message); trace("\n"); } } /** * print a trace * @param message message to trace */ static void trace(String message) { if (m_traceout != null) { m_traceout.print(message); } } /** * print a trace * @param e exception to trace */ static void trace(Exception e) { if (m_traceout != null) { e.printStackTrace(m_traceout); } } /** * Clone a dictionary * * @param dictionary The dictionary to clone * @return a copy of the dicionary */ private Dictionary cloneProperties(Dictionary dictionary){ Dictionary properties=new Hashtable(); if (dictionary == null) { properties = new Hashtable(); } else { Enumeration enumeration=dictionary.keys(); while(enumeration.hasMoreElements()){ Object key=enumeration.nextElement(); Object value=dictionary.get(key); properties.put(key,value); } } return properties; } /** * This class enables calls to Producer.consumersConnected and Consumer.producersConnected * to be done asynchronously * * p.333 "The WireAdmin service can call the consumersConnected or producersConnected * methods during the registration of the consumer of producer service" * **/ class AsyncMethodCaller implements Runnable { private boolean m_stop = false; private List m_methodCallStack = new ArrayList(); public void run() { while (!m_stop) { Object nextTarget[] = null; synchronized (m_methodCallStack) { while (m_methodCallStack.size() == 0) { try { m_methodCallStack.wait(); } catch (InterruptedException ex) { // Ignore. } } nextTarget = (Object[]) m_methodCallStack.remove(0); } if(nextTarget[0] instanceof Producer) { try { ((Producer)nextTarget[0]).consumersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } // Removed else because nextTarget can be both producer and consumer if(nextTarget[0] instanceof Consumer) { try { ((Consumer)nextTarget[0]).producersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } } } /** * Place a call to Consumer.producersConnected on the stack * * @param c the consumer * @param wires the wires */ public void producersConnected(Consumer c,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{c,wires}); m_methodCallStack.notify(); } } /** * Place a call to Producer.consumersConnected on the stack * * @param p the producer * @param wires the wires */ public void consumersConnected(Producer p,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{p,wires}); m_methodCallStack.notify(); } } /** * stop the dispatcher * */ void stop() { m_stop = true; } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 12042 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/wireadmin/src/main/java/org/apache/felix/wireadmin/WireAdminImpl.java/#L71-L1037 | 1 | 1807 | 12042 | critical |
| 552 | {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WireAdminImpl implements WireAdmin, ServiceListener { private BundleContext m_bundleContext; // A Map containing a service reference associated to a producer and a List // of wire objects private Map m_consumers = new HashMap(); /* ServiceReferences, List */ private Map m_producers = new HashMap(); /* ServiceReferences, List */ private List m_wires; // List containing the wires //private BindingController wireAdminListenersBindingController; // Filter corresponding to a consumer service private Filter m_consumerFilter; // Filter corresponding to a producer service private Filter m_producerFilter; // EventManager private EventManager m_eventManager; private static int m_wireCount = 0; private AsyncMethodCaller m_asyncMethodCaller = new AsyncMethodCaller(); //m_eventDispatcher.stop(); private static PrintStream m_traceout = null; private static PrintStream m_errorout = System.err; /** * Constructor with package visibility * * @param bundleContext the bundle context */ WireAdminImpl(BundleContext bundleContext) { m_bundleContext = bundleContext; if(bundleContext.getProperty("fr.imag.adele.wireadmin.trace") != null) { String value = bundleContext.getProperty("fr.imag.adele.wireadmin.trace"); if(value.equals("true")) { m_traceout = System.out; } } // Create the event manager (the event manager will start its own thread) m_eventManager = new EventManager(m_bundleContext); try { m_producerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Producer)"); m_consumerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Consumer)"); } catch (InvalidSyntaxException e) { // never thrown since LDAP expressions are correct } // Recover persistent wires getPersistentWires(); // Activate thread that does asynchronous calls to // the producersConnected and consummersConnected methods new Thread(m_asyncMethodCaller).start(); // Gets all producers and consumers that are present at the // moment the wire admin is created try { // Registration for events must be done first, as some service // can be registered during initialization m_bundleContext.addServiceListener(this,"(|"+m_producerFilter.toString()+m_consumerFilter.toString()+")"); // Replacement for the two following lines which work under OSCAR, // but not work under IBM's SMF //m_bundleContext.addServiceListener(this,m_consumerFilter.toString()); //m_bundleContext.addServiceListener(this,m_producerFilter.toString()); // Get all producers ServiceReference[] producerRefs = m_bundleContext.getServiceReferences(Producer.class.getName(),null); if(producerRefs!=null) { // lock the producers Map to avoid concurrent modifications due // to service events synchronized(m_producers) { for(int i=0;iWire object that connects a Producer * service to a Consumer service. * * The Producer service and Consumer service do not * have to be registered when the Wire object is created. * * The Wire configuration data must be persistently stored. * All Wire connections are reestablished when the * WireAdmin service is registered. * A Wire can be permanently removed by using the * {@link #deleteWire} method. * * The Wire object's properties must have case * insensitive String objects as keys (like the Framework). * However, the case of the key must be preserved. * The type of the value of the property must be one of the following: * * * type = basetype * | vector | arrays * * basetype = String | Integer | Long * | Float | Double | Byte * | Short | Character * | Boolean * * primitive = long | int | short * | char | byte | double | float * * arrays = primitive '[]' | basetype '[]' * * vector = Vector of basetype * * * The WireAdmin service must automatically add the * following Wire properties: * * * {@link WireConstants#WIREADMIN_PID} set to the value of the Wire object's * persistent identity (PID). This value is generated by the * Wire Admin service when a Wire object is created. * * * {@link WireConstants#WIREADMIN_PRODUCER_PID} set to the value of * Producer service's PID. * * * {@link WireConstants#WIREADMIN_CONSUMER_PID} set to the value of * Consumer service's PID. * * * If the properties argument * already contains any of these keys, then the supplied values * are replaced with the values assigned by the Wire Admin service. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_CREATED} * after the new Wire object becomes available from {@link #getWires}. * * @param producerPID The service.pid of the Producer service * to be connected to the Wire object. * @param consumerPID The service.pid of the Consumer service * to be connected to the Wire object. * @param properties The Wire object's properties. This argument may be null * if the caller does not wish to define any Wire object's properties. * @return The Wire object for this connection. * @throws java.lang.IllegalArgumentException If * properties contains case variants of the same key name. */ public Wire createWire(String producerPID, String consumerPID, Dictionary props) { ServiceReference producerServiceRef = null; ServiceReference consumerServiceRef = null; Dictionary properties; if(props == null) { properties = new Hashtable(); } else { //Clone the dictionary properties = cloneProperties(props); } // Addition of mandatory properties properties.put(WireConstants.WIREADMIN_CONSUMER_PID, consumerPID); properties.put(WireConstants.WIREADMIN_PRODUCER_PID, producerPID); properties.put(WireConstants.WIREADMIN_PID, generateWirePID()); // p.327 "Wire objects can be created when the producer or consumer // service is not registered WireImpl wire = new WireImpl(producerPID, consumerPID, properties); // Initialize the wire wire.initialize(m_bundleContext,m_eventManager); // Add the wire to the list synchronized(m_wires) { m_wires.add(wire); } // p. 357 "The Wire Admin service must broadcast a WireAdminEvent of // type WireAdminEvent.WIRE_CREATED after the new Wire object becomes // available from getWires(java.lang.String)." m_eventManager.fireEvent(WireAdminEvent.WIRE_CREATED,wire); synchronized (m_producers) { Iterator producerIterator = m_producers.keySet().iterator(); while(producerIterator.hasNext()) { producerServiceRef = (ServiceReference) producerIterator.next(); if (producerServiceRef.getProperty(Constants.SERVICE_PID).equals(producerPID)) { wire.bindProducer(producerServiceRef); break; } } } synchronized (m_consumers) { Iterator consumerIterator = m_consumers.keySet().iterator(); while(consumerIterator.hasNext()) { consumerServiceRef = (ServiceReference) consumerIterator.next(); if (consumerServiceRef.getProperty(Constants.SERVICE_PID).equals(consumerPID)) { wire.bindConsumer(consumerServiceRef); break; } } } // p.327 If both Producer and Consumer services are registered, they are // connected by the wire admin service. if(wire.isConnected()) { List wires = (List) m_producers.get(producerServiceRef); wires.add(wire); m_asyncMethodCaller.consumersConnected(wire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(consumerServiceRef); wires.add(wire); m_asyncMethodCaller.producersConnected(wire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // Newly created wires are immediately persisted to avoid information // loss in case of crashes. (spec not clear about this) persistWires(); return wire; } /** * Delete a Wire object. * * The Wire object representing a connection between * a Producer service and a Consumer service must be * removed. * The persistently stored configuration data for the Wire object * must destroyed. The Wire object's method {@link Wire#isValid} will return false * after it is deleted. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_DELETED} * after the Wire object becomes invalid. * * @param wire The Wire object which is to be deleted. */ public void deleteWire(Wire wire) { if(m_wires.contains(wire)) { WireImpl wireImpl = (WireImpl) wire; m_wires.remove(wire); if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } wireImpl.invalidate(); // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_DELETED,wireImpl); // Persist state to avoid losses in case of crashes (spec not clear about this). persistWires(); } else { traceln("WireAdminImpl: Cannot delete a wire that is not managed by this service"); } } /** * Update the properties of a Wire object. * * The persistently stored configuration data for the Wire object * is updated with the new properties and then the Consumer and Producer * services will be called at the respective {@link Consumer#producersConnected} * and {@link Producer#consumersConnected} methods. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_UPDATED} * after the updated properties are available from the Wire object. * * @param wire The Wire object which is to be updated. * @param properties The new Wire object's properties or null if no properties are required. */ public void updateWire(Wire wire, Dictionary props) { if(m_wires.contains(wire) == false) { traceln("WireAdminImpl: Cannot update a wire that is not managed by this service"); return; } // Clone the dictionary Dictionary properties = cloneProperties(props); // Put again the mandatory properties, in case they are not set properties.put(WireConstants.WIREADMIN_CONSUMER_PID,wire.getProperties().get(WireConstants.WIREADMIN_CONSUMER_PID)); properties.put(WireConstants.WIREADMIN_PRODUCER_PID,wire.getProperties().get(WireConstants.WIREADMIN_PRODUCER_PID)); properties.put(WireConstants.WIREADMIN_PID,wire.getProperties().get(WireConstants.WIREADMIN_PID)); WireImpl wireImpl = (WireImpl) wire; wireImpl.updateProperties(properties); // Call methods on Consumer and Producer if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_UPDATED,wireImpl); } /** * Return the Wire objects that match the given filter. * * The list of available Wire objects is matched against the * specified filter. Wire objects which match the * filter must be returned. These Wire objects are not necessarily * connected. The Wire Admin service should not return * invalid Wire objects, but it is possible that a Wire * object is deleted after it was placed in the list. * * The filter matches against the Wire object's properties including * {@link WireConstants#WIREADMIN_PRODUCER_PID}, {@link WireConstants#WIREADMIN_CONSUMER_PID} * and {@link WireConstants#WIREADMIN_PID}. * * @param filter Filter string to select Wire objects * or null to select all Wire objects. * @return An array of Wire objects which match the filter * or null if no Wire objects match the filter. * @throws org.osgi.framework.InvalidSyntaxException If the specified filter * has an invalid syntax. * @see org.osgi.framework.Filter */ public Wire[] getWires(String filter) throws InvalidSyntaxException { List res = null; if (filter == null) { return (Wire [])m_wires.toArray(new Wire[m_wires.size()]); } else { Filter tempFilter = m_bundleContext.createFilter(filter); Iterator iter = m_wires.iterator(); while (iter.hasNext()) { WireImpl currentWire = (WireImpl) iter.next(); if (tempFilter.match(currentWire.getProperties())) { if (res == null) { res = new ArrayList(); } res.add(currentWire); } } } if (res == null) { return null; } else { return (Wire [])res.toArray(new Wire[res.size()]); } } /** * listens Producer and Consumer services changes * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent) */ public void serviceChanged(ServiceEvent e) { ServiceReference serviceRef = e.getServiceReference(); // A consumer service changed if (m_consumerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("consumer registered"); List wires = new ArrayList(); synchronized(m_consumers) { m_consumers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived consumer currentWire.bindConsumer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.add(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } } } if(!called) { // P. 329 "If the Consumer service has no Wire objects attached when it // is registered, the WireAdmin service must always call producersConnected(null) m_asyncMethodCaller.producersConnected((Consumer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("consumer unregistering"); synchronized(m_consumers) { m_consumers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindConsumer(); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.remove(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } else { currentWire.unbindConsumer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to consumer service modification traceln("consumer service modified"); break; } } // Removed else to manage services which are both producers AND consumers if (m_producerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("producer registered"); List wires = new ArrayList(); synchronized(m_producers) { m_producers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived producer currentWire.bindProducer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.add(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } } } if(!called) { // P. 329 "If the Producer service has no Wire objects attached when it // is registered, the WireAdmin service must always call consumersConnected(null) m_asyncMethodCaller.consumersConnected((Producer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("Producer unregistering"); synchronized(m_producers) { m_producers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindProducer(); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.remove(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } else { currentWire.unbindProducer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to producer service modification traceln("producer service modified"); break; } } } /** * release all references before stop */ synchronized void releaseAll() { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.invalidate(); } Iterator producerIt = m_producers.keySet().iterator(); while (producerIt.hasNext()) { ServiceReference producerRef = (ServiceReference) producerIt.next(); ((Producer)m_bundleContext.getService(producerRef)).consumersConnected(null); } Iterator consumerIt = m_consumers.keySet().iterator(); while (consumerIt.hasNext()) { ServiceReference consumerRef = (ServiceReference) consumerIt.next(); ((Consumer)m_bundleContext.getService(consumerRef)).producersConnected(null); } // Stop the thread m_asyncMethodCaller.stop(); // Notify the event manager so that it stops its thread m_eventManager.stop(); persistWires(); } /** * This method generates a PID. The pid is generated from the bundle id, * a hash code from the current time and a counter. * * @return a wire PID */ private String generateWirePID() { Date d = new Date(); String PID="wire."+m_bundleContext.getBundle().getBundleId()+d.hashCode()+m_wireCount; m_wireCount ++; // Maybe the counter should go above 9? if(m_wireCount>9) { m_wireCount = 0; } return PID; } /** * Recover persistent wires * */ private void getPersistentWires() { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(m_bundleContext.getDataFile("wires.ser"))); m_wires = (ArrayList) ois.readObject(); ois.close(); if(m_wires!=null) { traceln("Deserialized "+m_wires.size()+" wires"); Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.initialize(m_bundleContext,m_eventManager); } } else { traceln("Couldn't Deserialize wires"); m_wires = new ArrayList(); } } catch(FileNotFoundException ex) { // do not show anything as this exception is thrown every // time the wire admin service is launched for the first // time m_wires = new ArrayList(); } catch(Exception ex) { trace(ex); m_wires = new ArrayList(); } } /** * Persist existing wires * */ private void persistWires() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(m_bundleContext.getDataFile("wires.ser"))); oos.writeObject(m_wires); oos.close(); traceln("Serialized "+m_wires.size()+" wires"); } catch(Exception ex) { trace(ex); } } /** * print an error * @param message message to error */ static void error(String message) { if (m_errorout != null) { m_errorout.println(message); } } /** * print a trace * @param message message to trace */ static void traceln(String message) { if (m_traceout != null) { trace(message); trace("\n"); } } /** * print a trace * @param message message to trace */ static void trace(String message) { if (m_traceout != null) { m_traceout.print(message); } } /** * print a trace * @param e exception to trace */ static void trace(Exception e) { if (m_traceout != null) { e.printStackTrace(m_traceout); } } /** * Clone a dictionary * * @param dictionary The dictionary to clone * @return a copy of the dicionary */ private Dictionary cloneProperties(Dictionary dictionary){ Dictionary properties=new Hashtable(); if (dictionary == null) { properties = new Hashtable(); } else { Enumeration enumeration=dictionary.keys(); while(enumeration.hasMoreElements()){ Object key=enumeration.nextElement(); Object value=dictionary.get(key); properties.put(key,value); } } return properties; } /** * This class enables calls to Producer.consumersConnected and Consumer.producersConnected * to be done asynchronously * * p.333 "The WireAdmin service can call the consumersConnected or producersConnected * methods during the registration of the consumer of producer service" * **/ class AsyncMethodCaller implements Runnable { private boolean m_stop = false; private List m_methodCallStack = new ArrayList(); public void run() { while (!m_stop) { Object nextTarget[] = null; synchronized (m_methodCallStack) { while (m_methodCallStack.size() == 0) { try { m_methodCallStack.wait(); } catch (InterruptedException ex) { // Ignore. } } nextTarget = (Object[]) m_methodCallStack.remove(0); } if(nextTarget[0] instanceof Producer) { try { ((Producer)nextTarget[0]).consumersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } // Removed else because nextTarget can be both producer and consumer if(nextTarget[0] instanceof Consumer) { try { ((Consumer)nextTarget[0]).producersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } } } /** * Place a call to Consumer.producersConnected on the stack * * @param c the consumer * @param wires the wires */ public void producersConnected(Consumer c,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{c,wires}); m_methodCallStack.notify(); } } /** * Place a call to Producer.consumersConnected on the stack * * @param p the producer * @param wires the wires */ public void consumersConnected(Producer p,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{p,wires}); m_methodCallStack.notify(); } } /** * stop the dispatcher * */ void stop() { m_stop = true; } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 5572 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/wireadmin/src/main/java/org/apache/felix/wireadmin/WireAdminImpl.java/#L71-L1037 | 1 | 552 | 5572 | critical |
| 2529 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14731 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 2 | 2529 | 14731 | minor |
| 3823 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 9798 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L54340-L54409 | 1 | 3823 | 9798 | minor | ||
| 1597 | YES I found bad spells, the detected bad spells are: 1. Long method 2. Feature envy 3. Not following proper naming conventions of methods and variables 4. Deprecated methods still present in the code 5. Use of anonymous inner classes instead of named classes for functions 6. Unnecessary use of SuppressWarnings annotation 7. Lack of proper documentation for methods and classes 8. Lack of separation of concerns in the code (e.g. having persistence workaround code mixed with function code) 9. Code duplication (e.g. the append and prepend methods have similar implementations) 10. Not following standard Java coding standards (e.g. using protected access modifier for inner classes) 11. Lack of use of functional interfaces instead of Object types for function parameters 12. Use of null values without proper checks 13. Not utilizing built-in functions from the Functions class 14. Using inner classes instead of separate classes for different functions 15. Not utilizing Java 8 features such as lambda expressions and streams for improved readability and efficiency. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StringFunctions { /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function appendOld(final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function prependOld(final String prefix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterForArrayOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function, String> joinerOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function, String>() { public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function joinerForArrayOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function lengthOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function surroundOld(final String prefix, final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function trimOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toLowerCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toLowerCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toUpperCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toUpperCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function convertCaseOld(final CaseFormat src, final CaseFormat target) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return src.to(target, input); } }; } public static Function append(final String suffix) { return new AppendFunction(checkNotNull(suffix, "suffix")); } private static class AppendFunction implements Function { private final String suffix; public AppendFunction(String suffix) { this.suffix = suffix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; public static Function prepend(final String prefix) { return new PrependFunction(checkNotNull(prefix, "prefix")); } protected static class PrependFunction implements Function { private final String prefix; public PrependFunction(String prefix) { this.prefix = prefix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } } /** given e.g. "hello %s" returns a function which will insert a string into that pattern */ public static Function formatter(final String pattern) { return new FormatterFunction(pattern); } protected static class FormatterFunction implements Function { private final String pattern; FormatterFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object input) { return String.format(pattern, input); } }; /** given e.g. "hello %s %s" returns a function which will insert an array of two strings into that pattern */ public static Function formatterForArray(final String pattern) { return new FormatterForArrayFunction(checkNotNull(pattern, "pattern")); } protected static class FormatterForArrayFunction implements Function { private final String pattern; public FormatterForArrayFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object[] input) { return String.format(pattern, input); } } /** * Given e.g. "hello %s %s" returns a function which will insert an Iterable of two strings into that pattern * * @since 0.9.0 */ public static Function, String> formatterForIterable(final String pattern) { return new FormatterForIterableFunction(pattern); } protected static class FormatterForIterableFunction implements Function, String> { final String pattern; public FormatterForIterableFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Iterable input) { Object[] arr = (input == null) ? null : Iterables.toArray(input, Object.class); return String.format(pattern, arr); } } /** joins the given objects in a collection as a toString with the given separator */ public static Function, String> joiner(final String separator) { return new JoinerFunction(separator); } private static class JoinerFunction implements Function, String> { private final String separator; public JoinerFunction(String separator) { this.separator = separator; } public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } } /** joins the given objects as a toString with the given separator, but expecting an array of objects, not a collection */ public static Function joinerForArray(final String separator) { return new JoinerForArrayFunction(checkNotNull(separator, "separator")); } private static class JoinerForArrayFunction implements Function { private final String separator; protected JoinerForArrayFunction(String separator) { this.separator = separator; } public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } } /** provided here as a convenience; prefer {@link Functions#toStringFunction()} */ public static Function toStringFunction() { return Functions.toStringFunction(); } /** returns function which gives length of input, with -1 for nulls */ public static Function length() { return new LengthFunction(); } protected static class LengthFunction implements Function { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } } /** Surrounds an input string with the given prefix and suffix */ public static Function surround(final String prefix, final String suffix) { Preconditions.checkNotNull(prefix); Preconditions.checkNotNull(suffix); return new SurroundFunction(prefix, suffix); } protected static class SurroundFunction implements Function { private final String prefix; private final String suffix; public SurroundFunction(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } } public static Function trim() { return new TrimFunction(); } protected static class TrimFunction implements Function { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } } public static Function toLowerCase() { return new LowerCaseFunction(); } protected static class LowerCaseFunction implements Function { @Override public String apply(String input) { return input.toLowerCase(); } } public static Function toUpperCase() { return new UpperCaseFunction(); } protected static class UpperCaseFunction implements Function { @Override public String apply(String input) { return input.toUpperCase(); } } public static Function convertCase(final CaseFormat src, final CaseFormat target) { return new ConvertCaseFunction(checkNotNull(src, "src"), checkNotNull(target, "target")); } protected static class ConvertCaseFunction implements Function { private final CaseFormat src; private final CaseFormat target; public ConvertCaseFunction(CaseFormat src, CaseFormat target) { this.src = src; this.target = target; } @Override public String apply(String input) { return src.to(target, input); } } public static class RegexReplacer implements Function { private final String pattern; private final String replacement; public RegexReplacer(String pattern, String replacement) { this.pattern = pattern; this.replacement = replacement; } @Nullable @Override public String apply(@Nullable String s) { return Strings.replaceAllRegex(s, pattern, replacement); } } } |
blob | Long method2 Feature envy3 Not following proper naming conventions of methods and variables4 Deprecated methods still present in the code5 Use of anonymous inner classes instead of named classes for functions6 Unnecessary use of SuppressWarnings annotation7 Lack of proper documentation for methods and classes8 Lack of separation of concerns in the code (eg having persistence workaround code mixed with function code)9 Code duplication (eg the append and prepend methods have similar implementations) | t | f | f | . Long method2. Feature envy3. Not following proper naming conventions of methods and variables4. Deprecated methods still present in the code5. Use of anonymous inner classes instead of named classes for functions6. Unnecessary use of SuppressWarnings annotation7. Lack of proper documentation for methods and classes8. Lack of separation of concerns in the code (e.g. having persistence workaround code mixed with function code)9. Code duplication (e.g. the append and prepend methods have similar implementations) | blob | 0 | 11414 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java/#L32-L415 | 2 | 1597 | 11414 | major |
| 746 | YES I found bad smells: 1. Long method, 2. Feature envy, 3. Code duplication, 4. Inefficient use of exception handling, 5. Inconsistent formatting, 6. Poor variable names, 7. Tight coupling through static variables, 8. Use of hard-coded values, 9. Inefficient use of nested try-catch blocks, 10. Insufficient comments/documentation, 11. Use of unneeded wrapper method for Supplier class, 12. Unclear logic/flow, 13. Inconsistent use of exception handling, 14. Unused/unnecessary code, 15. Poor use of access modifiers, 16. Poor exception handling practices, 17. Unnecessary use of AccessController. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class XPathFactoryFinder { private static final String DEFAULT_PACKAGE = "com.sun.org.apache.xpath.internal"; /** debug support code. */ private static boolean debug = false; static { // Use try/catch block to support applets try { debug = SecuritySupport.getSystemProperty("jaxp.debug") != null; } catch (Exception unused) { debug = false; } } /** * Cache properties for performance. */ private static final Properties cacheProps = new Properties(); /** * First time requires initialization overhead. */ private volatile static boolean firstTime = true; /** * Conditional debug printing. * * @param msgGen Supplier function that returns debug message */ private static void debugPrintln(Supplier msgGen) { if (debug) { System.err.println("JAXP: " + msgGen.get()); } } /** * ClassLoader to use to find XPathFactory. */ private final ClassLoader classLoader; /** * Constructor that specifies ClassLoader to use * to find XPathFactory. * * @param loader * to be used to load resource and {@link XPathFactory} * implementations during the resolution process. * If this parameter is null, the default system class loader * will be used. */ public XPathFactoryFinder(ClassLoader loader) { this.classLoader = loader; if( debug ) { debugDisplayClassLoader(); } } private void debugDisplayClassLoader() { try { if( classLoader == SecuritySupport.getContextClassLoader() ) { debugPrintln(() -> "using thread context class loader ("+classLoader+") for search"); return; } } catch( Throwable unused ) { // getContextClassLoader() undefined in JDK1.1 } if( classLoader==ClassLoader.getSystemClassLoader() ) { debugPrintln(() -> "using system class loader ("+classLoader+") for search"); return; } debugPrintln(() -> "using class loader ("+classLoader+") for search"); } /** * Creates a new {@link XPathFactory} object for the specified * object model. * * @param uri * Identifies the underlying object model. * * @return null if the callee fails to create one. * * @throws NullPointerException * If the parameter is null. */ public XPathFactory newFactory(String uri) throws XPathFactoryConfigurationException { if (uri == null) { throw new NullPointerException(); } XPathFactory f = _newFactory(uri); if (f != null) { debugPrintln(()->"factory '" + f.getClass().getName() + "' was found for " + uri); } else { debugPrintln(()->"unable to find a factory for " + uri); } return f; } /** * Lookup a {@link XPathFactory} for the given object model. * * @param uri identifies the object model. * * @return {@link XPathFactory} for the given object model. */ private XPathFactory _newFactory(String uri) throws XPathFactoryConfigurationException { XPathFactory xpathFactory = null; String propertyName = SERVICE_CLASS.getName() + ":" + uri; // system property look up try { debugPrintln(()->"Looking up system property '"+propertyName+"'" ); String r = SecuritySupport.getSystemProperty(propertyName); if(r!=null) { debugPrintln(()->"The value is '"+r+"'"); xpathFactory = createInstance(r); if (xpathFactory != null) { return xpathFactory; } } else debugPrintln(()->"The property is undefined."); } catch( Throwable t ) { if( debug ) { debugPrintln(()->"failed to look up system property '"+propertyName+"'" ); t.printStackTrace(); } } String javah = SecuritySupport.getSystemProperty( "java.home" ); String configFile = javah + File.separator + "conf" + File.separator + "jaxp.properties"; // try to read from $java.home/conf/jaxp.properties try { if(firstTime){ synchronized(cacheProps){ if(firstTime){ File f=new File( configFile ); firstTime = false; if(SecuritySupport.doesFileExist(f)){ debugPrintln(()->"Read properties file " + f); cacheProps.load(SecuritySupport.getFileInputStream(f)); } } } } final String factoryClassName = cacheProps.getProperty(propertyName); debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties"); if (factoryClassName != null) { xpathFactory = createInstance(factoryClassName); if(xpathFactory != null){ return xpathFactory; } } } catch (Exception ex) { if (debug) { ex.printStackTrace(); } } // Try with ServiceLoader assert xpathFactory == null; xpathFactory = findServiceProvider(uri); // The following assertion should always be true. // Uncomment it, recompile, and run with -ea in case of doubts: // assert xpathFactory == null || xpathFactory.isObjectModelSupported(uri); if (xpathFactory != null) { return xpathFactory; } // platform default if(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) { debugPrintln(()->"attempting to use the platform default W3C DOM XPath lib"); return new XPathFactoryImpl(); } debugPrintln(()->"all things were tried, but none was found. bailing out."); return null; } /** Create class using appropriate ClassLoader. * * @param className Name of class to create. * @return Created class or null. */ private Class createClass(String className) { Class clazz; // make sure we have access to restricted packages boolean internal = false; if (System.getSecurityManager() != null) { if (className != null && className.startsWith(DEFAULT_PACKAGE)) { internal = true; } } // use approprite ClassLoader try { if (classLoader != null && !internal) { clazz = Class.forName(className, false, classLoader); } else { clazz = Class.forName(className); } } catch (Throwable t) { if(debug) { t.printStackTrace(); } return null; } return clazz; } /** * Creates an instance of the specified and returns it. * * @param className * fully qualified class name to be instantiated. * * @return null * if it fails. Error messages will be printed by this method. */ XPathFactory createInstance(String className) throws XPathFactoryConfigurationException { XPathFactory xPathFactory = null; debugPrintln(()->"createInstance(" + className + ")"); // get Class from className Class clazz = createClass(className); if (clazz == null) { debugPrintln(()->"failed to getClass(" + className + ")"); return null; } debugPrintln(()->"loaded " + className + " from " + which(clazz)); // instantiate Class as a XPathFactory try { xPathFactory = (XPathFactory) clazz.getConstructor().newInstance(); } catch (ClassCastException | IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { debugPrintln(()->"could not instantiate " + clazz.getName()); if (debug) { ex.printStackTrace(); } return null; } return xPathFactory; } // Call isObjectModelSupportedBy with initial context. private boolean isObjectModelSupportedBy(final XPathFactory factory, final String objectModel, AccessControlContext acc) { return AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { return factory.isObjectModelSupported(objectModel); } }, acc); } /** * Finds a service provider subclass of XPathFactory that supports the * given object model using the ServiceLoader. * * @param objectModel URI of object model to support. * @return An XPathFactory supporting the specified object model, or null * if none is found. * @throws XPathFactoryConfigurationException if a configuration error is found. */ private XPathFactory findServiceProvider(final String objectModel) throws XPathFactoryConfigurationException { assert objectModel != null; // store current context. final AccessControlContext acc = AccessController.getContext(); try { return AccessController.doPrivileged(new PrivilegedAction() { public XPathFactory run() { final ServiceLoader loader = ServiceLoader.load(SERVICE_CLASS); for (XPathFactory factory : loader) { // restore initial context to call // factory.isObjectModelSupportedBy if (isObjectModelSupportedBy(factory, objectModel, acc)) { return factory; } } return null; // no factory found. } }); } catch (ServiceConfigurationError error) { throw new XPathFactoryConfigurationException(error); } } private static final Class SERVICE_CLASS = XPathFactory.class; // Used for debugging purposes private static String which( Class clazz ) { return SecuritySupport.getClassSource(clazz); } } |
blob | Long method, 2 Feature envy, 3 Code duplication, 4 Inefficient use of exception handling, 5 Inconsistent formatting, 6 Poor variable names, 7 Tight coupling through static variables, 8 Use of hard-coded values, 9 Inefficient use of nested try-catch blocks, | t | f | f | . Long method, 2. Feature envy, 3. Code duplication, 4. Inefficient use of exception handling, 5. Inconsistent formatting, 6. Poor variable names, 7. Tight coupling through static variables, 8. Use of hard-coded values, 9. Inefficient use of nested try-catch blocks, | blob | 0 | 7014 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java/#L46-L357 | 2 | 746 | 7014 | major |
| 2659 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorTestCaseFinder { private static final Logger log = LoggerFactory.getLogger(IteratorTestCaseFinder.class); /** * Instantiates all test cases provided. * * @return A list of {@link IteratorTestCase}s. */ public static List findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet classes = cp .getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List testCases = new ArrayList<>(); // final Set> classes = // reflections.getSubTypesOf(IteratorTestCase.class); for (ClassInfo classInfo : classes) { Class clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; } } |
blob | long method | t | t | f | long method | blob | 0 | 15189 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/iterator-test-harness/src/main/java/org/apache/accumulo/iteratortest/IteratorTestCaseFinder.java/#L35-L81 | 1 | 2659 | 15189 | minor |
| 786 | {"result": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 7505 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 1 | 786 | 7505 | minor |
| 2487 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Not specified | f | f | f | false | 0 | 14611 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 2487 | 14611 | minor | |
| 2353 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | long method | t | t | f | long method | blob | 0 | 14224 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2353 | 14224 | minor |
| 162 | {"response": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BatchWriterReplicationReplayer implements AccumuloReplicationReplayer { private static final Logger log = LoggerFactory.getLogger(BatchWriterReplicationReplayer.class); @Override public long replicateLog(ClientContext context, String tableName, WalEdits data) throws RemoteReplicationException { final LogFileKey key = new LogFileKey(); final LogFileValue value = new LogFileValue(); final long memoryInBytes = context.getConfiguration() .getAsBytes(Property.TSERV_REPLICATION_BW_REPLAYER_MEMORY); BatchWriter bw = null; long mutationsApplied = 0L; try { for (ByteBuffer edit : data.getEdits()) { DataInputStream dis = new DataInputStream(ByteBufferUtil.toByteArrayInputStream(edit)); try { key.readFields(dis); // TODO this is brittle because AccumuloReplicaSystem isn't actually calling // LogFileValue.write, but we're expecting // what we receive to be readable by the LogFileValue. value.readFields(dis); } catch (IOException e) { log.error("Could not deserialize edit from stream", e); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_DESERIALIZE, "Could not deserialize edit from stream"); } // Create the batchScanner if we don't already have one. if (bw == null) { BatchWriterConfig bwConfig = new BatchWriterConfig(); bwConfig.setMaxMemory(memoryInBytes); try { bw = context.createBatchWriter(tableName, bwConfig); } catch (TableNotFoundException e) { throw new RemoteReplicationException(RemoteReplicationErrorCode.TABLE_DOES_NOT_EXIST, "Table " + tableName + " does not exist"); } } log.info("Applying {} mutations to table {} as part of batch", value.mutations.size(), tableName); // If we got a ServerMutation, we have to make sure that we preserve the systemTimestamp // otherwise // the local system will assign a new timestamp. List mutationsCopy = new ArrayList<>(value.mutations.size()); long mutationsCopied = 0L; for (Mutation orig : value.mutations) { if (orig instanceof ServerMutation) { mutationsCopied++; ServerMutation origServer = (ServerMutation) orig; Mutation copy = new Mutation(orig.getRow()); for (ColumnUpdate update : orig.getUpdates()) { long timestamp; // If the update doesn't have a timestamp, pull it from the ServerMutation if (!update.hasTimestamp()) { timestamp = origServer.getSystemTimestamp(); } else { timestamp = update.getTimestamp(); } // TODO ACCUMULO-2937 cache the CVs if (update.isDeleted()) { copy.putDelete(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp); } else { copy.put(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp, update.getValue()); } } // We also need to preserve the replicationSource information to prevent cycles Set replicationSources = orig.getReplicationSources(); if (replicationSources != null && !replicationSources.isEmpty()) { for (String replicationSource : replicationSources) { copy.addReplicationSource(replicationSource); } } mutationsCopy.add(copy); } else { mutationsCopy.add(orig); } } log.debug("Copied {} mutations to ensure server-assigned timestamps are propagated", mutationsCopied); try { bw.addMutations(mutationsCopy); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } log.debug("{} mutations added to the BatchScanner", mutationsCopy.size()); mutationsApplied += mutationsCopy.size(); } } finally { if (bw != null) { try { bw.close(); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } } } log.info("Applied {} mutations in total to {}", mutationsApplied, tableName); return mutationsApplied; } } |
blob | long method | t | t | f | long method | blob | 0 | 1995 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/tserver/src/main/java/org/apache/accumulo/tserver/replication/BatchWriterReplicationReplayer.java/#L50-L171 | 1 | 162 | 1995 | major |
| 3052 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServerFormatListPDU extends BaseElement { protected ClipboardState state; public ServerFormatListPDU(String id, ClipboardState state) { super(id); this.state = state; } @Override public void handleData(ByteBuffer buf, Link link) { if (verbose) System.out.println("[" + this + "] INFO: Data received: " + buf + "."); parseFormatNames(buf); buf.unref(); // Automatically send request for text-based data to insert it into local // clipboard ClipboardDataFormat textFormat = ClipboardDataFormat.findBestTextFormat(state.serverClipboardDataFormats); if (textFormat != null) { // Send response: OK sendFormatListParseResponse(true); // Request data sendFormatDataRequest(textFormat); } else { // Send response: FAIL, we are not interested in this data sendFormatListParseResponse(false); } } /** * The Format Data Request PDU is sent by the recipient of the Format List * PDU. It is used to request the data for one of the formats that was listed * in the Format List PDU. */ protected void sendFormatDataRequest(ClipboardDataFormat textFormat) { if (verbose) System.out.println("[" + this + "] INFO: Sending request for data in following format: " + textFormat + "."); // Store data format to parse server response later state.serverRequestedFormat = textFormat; ByteBuffer buf = new ByteBuffer(12, true); // Type buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_DATA_REQUEST); // Message flags buf.writeShortLE(0); // Length buf.writeIntLE(4); // ID of chosen format buf.writeIntLE(textFormat.id); buf.trimAtCursor(); pushDataToPad(STDOUT, buf); } /** * The Format List Response PDU is sent as a reply to the Format List PDU. It * is used to indicate whether processing of the Format List PDU was * successful. * * @param b */ protected void sendFormatListParseResponse(boolean ok) { ByteBuffer buf = new ByteBuffer(8, true); // Type buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_LIST_RESPONSE); // Message flags buf.writeShortLE((ok) ? ServerClipRdrChannelRouter.CB_RESPONSE_OK : ServerClipRdrChannelRouter.CB_RESPONSE_FAIL); // Length buf.writeIntLE(0); buf.trimAtCursor(); pushDataToPad(STDOUT, buf); } protected void parseFormatNames(ByteBuffer buf) { // Set will not be modified after creation, so there is no need to make it // synchronous. Map formats = new HashMap(); while (buf.cursor < buf.length) { int id = buf.readSignedIntLE(); String name; if (state.serverUseLongFormatNames) { // Long format names in Unicode name = buf.readVariableWideString(RdpConstants.CHARSET_16); } else { Boolean asciiNames = (Boolean)buf.getMetadata(ServerClipRdrChannelRouter.ASCII_NAMES); if (asciiNames != null && asciiNames) { // Short format names in ASCII name = buf.readString(32, RdpConstants.CHARSET_8); } else { // Short format names in Unicode name = buf.readString(32, RdpConstants.CHARSET_16); } } // Store format in map by both ID and name (if name is not empty) formats.put(id, new ClipboardDataFormat(id, name)); if (name.length() > 0) formats.put(name, new ClipboardDataFormat(id, name)); } if (verbose) System.out.println("Server supports following formats for clipboard data: " + formats.values().toString() + "."); state.serverClipboardDataFormats = formats; } /** * Example. */ public static void main(String[] args) { // System.setProperty("streamer.Link.debug", "true"); System.setProperty("streamer.Element.debug", "true"); // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ byte[] packet = new byte[] { 0x02, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST (2) 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 (byte) 0xe0, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0xe0 = 224 bytes (byte) 0x8a, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc08a = 49290 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format" 0x45, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc145 = 49477 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x57, 0x00, 0x69, 0x00, 0x74, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x74, 0x00, 0x20, 0x00, 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x73, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format Without Objects" 0x43, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc143 = 49475 0x52, 0x00, 0x54, 0x00, 0x46, 0x00, 0x20, 0x00, 0x41, 0x00, 0x73, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "RTF As Text" 0x01, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 1 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0x0d = 13 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x04, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc004 = 49156 0x4e, 0x00, 0x61, 0x00, 0x74, 0x00, 0x69, 0x00, 0x76, 0x00, 0x65, 0x00, 0x00, 0x00, // "Native" 0x0e, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc00e = 49166 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x20, 0x00, 0x44, 0x00, 0x65, 0x00, 0x73, 0x00, 0x63, 0x00, 0x72, 0x00, 0x69, 0x00, 0x70, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Object Descriptor" 0x03, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 3 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x10, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 16 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" 0x07, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 7 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" }; /* @formatter:on */ MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element router = new ServerClipRdrChannelRouter("router"); ClipboardState state = new ClipboardState(); state.serverUseLongFormatNames = true; Element format_list = new ServerFormatListPDU("format_list", state); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { // Format List Response PDU 0x03, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST_RESPONSE (3) 0x01, 0x00, // CLIPRDR_HEADER::msgFlags = 0x0001 = CB_RESPONSE_OK 0x00, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0 bytes }, new byte[] { // Format Data Request PDU 0x04, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_DATA_REQUEST (4) 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 0x04, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 4 bytes 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_FORMAT_DATA_REQUEST::requestedFormatId // = 0x0d })); Pipeline pipeline = new PipelineImpl("test"); pipeline.add(source, router, format_list, sink); pipeline.link("source", "router >format_list", "format_list", "sink"); pipeline.runMainLoop("source", STDOUT, false, false); // Check state if (!(state.serverClipboardDataFormats.containsKey(49475) && state.serverClipboardDataFormats.containsKey("Rich Text Format"))) throw new RuntimeException("Server format list packet parsed incorrectly."); } } |
blob | long method | t | t | f | long method | blob | 0 | 3495 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/services/console-proxy/rdpconsole/src/main/java/rdpclient/clip/ServerFormatListPDU.java/#L32-L237 | 1 | 3052 | 3495 | minor |
| 955 | YES I found bad smells The bad smells are: 1. Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles. 2. Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class. 3. Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined. This can make the code difficult to understand and maintain. 4. Poor formatting - the code lacks proper indentation, making it difficult to read and understand. 5. No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it. 6. Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles2 Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class3 Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined This can make the code difficult to understand and maintain4 Poor formatting - the code lacks proper indentation, making it difficult to read and understand5 No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it6 Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase | t | f | f | . Mutator and Accessor methods - the class only contains getters and setters for its instance variables, which can indicate that the class is not following good object-oriented design principles.2. Meaningless variable names - the variable names "message", "code", and "t200" do not provide enough information about what they represent, making it difficult to understand the purpose of the class.3. Magic numbers - the code uses the number 200 multiple times, which are not clearly explained or defined. This can make the code difficult to understand and maintain.4. Poor formatting - the code lacks proper indentation, making it difficult to read and understand.5. No comments or documentation - there is no explanation or documentation for the purpose or functionality of the class, making it difficult for other developers to understand how to use it.6. Lack of cohesion - the class does not have a clear and specific responsibility, making it difficult to understand its purpose and how it fits into the overall codebase. | data class | 0 | 8535 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 2 | 955 | 8535 | major |
| 1777 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11957 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 2 | 1777 | 11957 | minor |
| 1983 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 12645 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 2 | 1983 | 12645 | major |
| 714 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class LazyIterate { private static final LazyIterable EMPTY_ITERABLE = Lists.immutable.empty().asLazy(); private LazyIterate() { throw new AssertionError("Suppress default constructor for noninstantiability"); } /** * Creates a deferred rich iterable for the specified iterable. */ public static LazyIterable adapt(Iterable iterable) { return new LazyIterableAdapter<>(iterable); } /** * Creates a deferred filtering iterable for the specified iterable. */ public static LazyIterable select(Iterable iterable, Predicate predicate) { return new SelectIterable<>(iterable, predicate); } /** * Creates a deferred negative filtering iterable for the specified iterable. */ public static LazyIterable reject(Iterable iterable, Predicate predicate) { return new RejectIterable<>(iterable, predicate); } public static LazyIterable selectInstancesOf(Iterable iterable, Class clazz) { return new SelectInstancesOfIterable<>(iterable, clazz); } /** * Creates a deferred transforming iterable for the specified iterable. */ public static LazyIterable collect( Iterable iterable, Function function) { return new CollectIterable<>(iterable, function); } /** * Creates a deferred flattening iterable for the specified iterable. */ public static LazyIterable flatCollect( Iterable iterable, Function> function) { return new FlatCollectIterable<>(iterable, function); } /** * Creates a deferred filtering and transforming iterable for the specified iterable. */ public static LazyIterable collectIf( Iterable iterable, Predicate predicate, Function function) { return LazyIterate.select(iterable, predicate).collect(function); } /** * Creates a deferred take iterable for the specified iterable using the specified count as the limit. */ public static LazyIterable take(Iterable iterable, int count) { return new TakeIterable<>(iterable, count); } /** * Creates a deferred drop iterable for the specified iterable using the specified count as the size to drop. */ public static LazyIterable drop(Iterable iterable, int count) { return new DropIterable<>(iterable, count); } /** * Creates a deferred takeWhile iterable for the specified iterable using the specified predicate. * Short circuits at the first element which does not satisfy the Predicate. * * @since 8.0 */ public static LazyIterable takeWhile(Iterable iterable, Predicate predicate) { return new TakeWhileIterable<>(iterable, predicate); } /** * Creates a deferred dropWhile iterable for the specified iterable using the specified count as the size to drop. * Short circuits at the first element which satisfies the Predicate. * * @since 8.0 */ public static LazyIterable dropWhile(Iterable iterable, Predicate predicate) { return new DropWhileIterable<>(iterable, predicate); } /** * Creates a deferred distinct iterable for the specified iterable. * * @since 5.0 */ public static LazyIterable distinct(Iterable iterable) { return new DistinctIterable<>(iterable); } /** * Combines iterables into a deferred composite iterable. */ public static LazyIterable concatenate(Iterable... iterables) { return CompositeIterable.with(iterables); } public static LazyIterable empty() { return (LazyIterable) EMPTY_ITERABLE; } public static LazyIterable> zip(Iterable as, Iterable bs) { return new ZipIterable<>(as, bs); } public static LazyIterable> zipWithIndex(Iterable iterable) { return new ZipWithIndexIterable<>(iterable); } public static LazyIterable> chunk(Iterable iterable, int size) { return new ChunkIterable<>(iterable, size); } /** * Creates a deferred tap iterable for the specified iterable. * * @since 6.0 */ public static LazyIterable tap(Iterable iterable, Procedure procedure) { return new TapIterable<>(iterable, procedure); } /** * Create a deferred cartesian product of the two specified iterables. * * See {@link LazyIterate#cartesianProduct(Iterable, Iterable, Function2)} about performance and presence of duplicates. * * @since 10.0 */ public static LazyIterable> cartesianProduct(Iterable iterable1, Iterable iterable2) { return LazyIterate.cartesianProduct(iterable1, iterable2, Tuples::pair); } /** * Create a deferred cartesian product of the two specified iterables. * * This operation has O(n^2) performance. * * The presence of duplicates in the resulting iterable is both dependent on the * presence of duplicates in the two specified iterables, and on the behaviour * of the terminating operation that is applied to the resulting lazy iterable. * * @since 10.0 */ public static LazyIterable cartesianProduct(Iterable iterable1, Iterable iterable2, Function2 function) { return LazyIterate.flatCollect(iterable1, first -> LazyIterate.collect(iterable2, second -> function.value(first, second))); } } |
blob | long method | t | t | f | long method | blob | 0 | 6804 | https://github.com/eclipse/eclipse-collections/blob/fa40c9aadbd36fb08f05a60b200e92ace40a7bfd/eclipse-collections/src/main/java/org/eclipse/collections/impl/utility/LazyIterate.java/#L47-L229 | 1 | 714 | 6804 | minor |
| 2460 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 14540 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 2 | 2460 | 14540 | major |
| 768 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | data class | t | t | f | data class | blob | 0 | 7237 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 1 | 768 | 7237 | minor |
| 3883 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Poor naming conventions 5. Lack of encapsulation 6. Inconsistency in coding style 7. Unnecessary use of static variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
blob | Long method 2 Feature envy 3 Duplicate code 4 Poor naming conventions 5 Lack of encapsulation 6 Inconsistency in coding style 7 Unnecessary use of static variables and methods | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Poor naming conventions 5. Lack of encapsulation 6. Inconsistency in coding style 7. Unnecessary use of static variables and methods | blob | 0 | 10140 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 3883 | 10140 | minor |
| 655 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6404 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 2 | 655 | 6404 | major |
| 32 | {"message": "YES, I found bad smells. the bad smells are:", "bad_smells": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 730 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 2 | 32 | 730 | critical |
| 1433 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10958 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 | 2 | 1433 | 10958 | minor |
| 194 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature Envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2230 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 | 2 | 194 | 2230 | minor |
| 5146 | {"message": "YES I found bad smells", "bad smells are: 1. Long method, 2. Feature envy:" : ["Long method", "Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14395 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 | 2 | 5146 | 14395 | major |
| 2137 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13258 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 2 | 2137 | 13258 | major |
| 3387 | { "input_code": "public class Example {\n\n public void exampleMethod() {\n int a = 5;\n int b = 10;\n System.out.println(\"Sum: \" + (a + b));\n }\n\n public void anotherMethod() {\n String message = \"Hello, World!\";\n System.out.println(message);\n }\n}", "detected_bad_smells": { "Long Method": true, "Data Class": false, "Blob": false, "Feature Envy": false } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | false | 0 | 6559 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L241837-L241908 | 1 | 3387 | 6559 | minor | ||
| 451 | YES I found bad smells the bad smells are: 1. Long method 2. Inconsistent naming conventions 3. Feature envy 4. Magic numbers 5. Poor encapsulation 6. Magic strings 7. Incomplete error handling 8. Complex conditional statements 9. Violation of single responsibility principle 10. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RemoteWasbDelegationTokenManager implements WasbDelegationTokenManager { /** * Configuration parameter name expected in the configuration * object to provide the url of the delegation token service to fetch the delegation tokens. */ public static final String KEY_DELEGATION_TOKEN_SERVICE_URLS = "fs.azure.delegation.token.service.urls"; /** * Configuration key to enable http retry policy for delegation token service calls. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY = "fs.azure.delegationtokenservice.http.retry.policy.enabled"; /** * Configuration key for delegation token service http retry policy spec. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY = "fs.azure.delegationtokenservice.http.retry.policy.spec"; /** * Default remote delegation token manager endpoint. */ private static final String DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT = "/tokenmanager/v1"; /** * Default for delegation token service http retry policy spec. */ private static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10,3,100,2"; private static final boolean DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = true; private static final Text WASB_DT_SERVICE_NAME = new Text("WASB_DT_SERVICE"); /** * Query parameter value for Getting delegation token http request */ private static final String GET_DELEGATION_TOKEN_OP = "GETDELEGATIONTOKEN"; /** * Query parameter value for renewing delegation token http request */ private static final String RENEW_DELEGATION_TOKEN_OP = "RENEWDELEGATIONTOKEN"; /** * Query parameter value for canceling the delegation token http request */ private static final String CANCEL_DELEGATION_TOKEN_OP = "CANCELDELEGATIONTOKEN"; /** * op parameter to represent the operation. */ private static final String OP_PARAM_KEY_NAME = "op"; /** * renewer parameter to represent the renewer of the delegation token. */ private static final String RENEWER_PARAM_KEY_NAME = "renewer"; /** * service parameter to represent the service which returns delegation tokens. */ private static final String SERVICE_PARAM_KEY_NAME = "service"; /** * token parameter to represent the delegation token. */ private static final String TOKEN_PARAM_KEY_NAME = "token"; private WasbRemoteCallHelper remoteCallHelper; private String[] dtServiceUrls; private boolean isSpnegoTokenCacheEnabled; public RemoteWasbDelegationTokenManager(Configuration conf) throws IOException { RetryPolicy retryPolicy = RetryUtils.getMultipleLinearRandomRetry(conf, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT); this.isSpnegoTokenCacheEnabled = conf.getBoolean(Constants.AZURE_ENABLE_SPNEGO_TOKEN_CACHE, true); remoteCallHelper = new SecureWasbRemoteCallHelper(retryPolicy, true, isSpnegoTokenCacheEnabled); this.dtServiceUrls = conf.getTrimmedStrings(KEY_DELEGATION_TOKEN_SERVICE_URLS); if (this.dtServiceUrls == null || this.dtServiceUrls.length <= 0) { throw new IOException( KEY_DELEGATION_TOKEN_SERVICE_URLS + " config not set" + " in configuration."); } } @Override public Token getDelegationToken( String renewer) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, GET_DELEGATION_TOKEN_OP) .addParameter(RENEWER_PARAM_KEY_NAME, renewer) .addParameter(SERVICE_PARAM_KEY_NAME, WASB_DT_SERVICE_NAME.toString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpGet.METHOD_NAME); return TokenUtils.toDelegationToken(JsonUtils.parse(responseBody)); } @Override public long renewDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, RENEW_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); Map parsedResp = JsonUtils.parse(responseBody); return ((Number) parsedResp.get("long")).longValue(); } @Override public void cancelDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, CANCEL_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); remoteCallHelper.makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); } } |
blob | Long method 2 Inconsistent naming conventions 3 Feature envy 4 Magic numbers 5 Poor encapsulation 6 Magic strings 7 Incomplete error handling 8 Complex conditional statements 9 Violation of single responsibility principle | t | f | f | . Long method 2. Inconsistent naming conventions 3. Feature envy 4. Magic numbers 5. Poor encapsulation 6. Magic strings 7. Incomplete error handling 8. Complex conditional statements 9. Violation of single responsibility principle | blob | 0 | 4407 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/security/RemoteWasbDelegationTokenManager.java/#L39-L169 | 2 | 451 | 4407 | minor |
| 1929 | {"message": "YES I found bad smells","bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
blob | data class | t | t | f | data class | blob | 0 | 12452 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 1929 | 12452 | major |
| 1855 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
blob | Long method | t | f | f | . Long method | blob | 0 | 12207 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 2 | 1855 | 12207 | minor |
| 842 | {"answer":"YES I found bad smells","bad smells are":["Blob","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 7803 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 1 | 842 | 7803 | minor |
| 4034 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
feature envy | the bad smells are: long method, data class | t | t | f | the bad smells are: long method, data class | feature envy | 0 | 10674 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 4034 | 10674 | major |
| 5516 | YES I found bad smells the bad smells are: 1. Blob 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
feature envy | Blob2 Long method | t | f | f | . Blob2. Long method | feature envy | 0 | 4261 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5516 | 4261 | major |
| 5431 | { "NO, I did not find any bad smell" : "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 15257 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 5431 | 15257 | major |
| 401 | { "message": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
feature envy | Not specified | f | f | f | false | 0 | 4102 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 401 | 4102 | minor | |
| 4098 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy - CommandShelvesets class has an excessive amount of dependencies and accesses many different classes. 3. Duplicate code - the variable shelvesetName is re-assigned multiple times. 4. Magic numbers/literals - there are multiple instances of strings being used without explanation or context. 5. Inconsistent formatting - there are multiple instances of inconsistent spacing and indentation throughout the code. 6. Poor variable naming - variable names such as "o" and "client" are not descriptive and do not convey their purpose. 7. Primitive obsession - there is a lack of object-oriented programming principles with excessive use of primitive data types instead of creating meaningful objects. 8. Unnecessary conditional statements - there are multiple if-statements that could be simplified or refactored. 9. Non-descriptive exception handling - some exceptions are caught and handled without providing meaningful error messages. 10. Unnecessary comments - there are redundant or unnecessary comments that do not add value to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | Long method2 Feature envy - CommandShelvesets class has an excessive amount of dependencies and accesses many different classes3 Duplicate code - the variable shelvesetName is re-assigned multiple times4 Magic numbers/literals - there are multiple instances of strings being used without explanation or context5 Inconsistent formatting - there are multiple instances of inconsistent spacing and indentation throughout the code6 Poor variable naming - variable names such as "o" and "client" are not descriptive and do not convey their purpose7 Primitive obsession - there is a lack of object-oriented programming principles with excessive use of primitive data types instead of creating meaningful objects8 Unnecessary conditional statements - there are multiple if-statements that could be simplified or refactored9 Non-descriptive exception handling - some exceptions are caught and handled without providing meaningful error messages | t | f | f | . Long method2. Feature envy - CommandShelvesets class has an excessive amount of dependencies and accesses many different classes.3. Duplicate code - the variable shelvesetName is re-assigned multiple times.4. Magic numbers/literals - there are multiple instances of strings being used without explanation or context.5. Inconsistent formatting - there are multiple instances of inconsistent spacing and indentation throughout the code.6. Poor variable naming - variable names such as "o" and "client" are not descriptive and do not convey their purpose.7. Primitive obsession - there is a lack of object-oriented programming principles with excessive use of primitive data types instead of creating meaningful objects.8. Unnecessary conditional statements - there are multiple if-statements that could be simplified or refactored.9. Non-descriptive exception handling - some exceptions are caught and handled without providing meaningful error messages. | blob | 0 | 10793 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 2 | 4098 | 10793 | minor |
| 2025 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | Long method, 2Magic numbers | t | f | f | .Long method, 2.Magic numbers | feature envy | 0 | 12800 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 2 | 2025 | 12800 | minor |
| 2113 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy (related to the MouseAdapter and MouseMoveListener) 3. Duplicate code (there are several sections of code that have very similar functions but are repeated) 4. Magic numbers (hard-coded numbers like 1, 2, 16, etc. which should be stored as constants for better readability) 5. Primitive obsession (the use of primitive data types instead of creating a separate class or object) 6. Inconsistent naming conventions (some variable names are camelCase while others are not) 7. Complex if-else statements (the if-else structure is convoluted and could be simplified) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } |
data class | Long method2 Feature envy (related to the MouseAdapter and MouseMoveListener)3 Duplicate code (there are several sections of code that have very similar functions but are repeated)4 Magic numbers (hard-coded numbers like | t | f | f | . Long method2. Feature envy (related to the MouseAdapter and MouseMoveListener)3. Duplicate code (there are several sections of code that have very similar functions but are repeated)4. Magic numbers (hard-coded numbers like | data class | 0 | 13191 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/swt/custom/TabbedPropertyList.java/#L116-L325 | 2 | 2113 | 13191 | minor |
| 2693 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 15309 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 2693 | 15309 | minor |
| 1566 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long Method | t | f | f | Long Method | data class | 0 | 11327 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 1566 | 11327 | minor |
| 5390 | , NO i did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 15151 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 5390 | 15151 | minor | ||
| 2563 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExplainTask extends Task implements Serializable { public static final String STAGE_DEPENDENCIES = "STAGE DEPENDENCIES"; private static final long serialVersionUID = 1L; public static final String EXPL_COLUMN_NAME = "Explain"; private final Set> visitedOps = new HashSet>(); private boolean isLogical = false; protected final Logger LOG; public ExplainTask() { super(); LOG = LoggerFactory.getLogger(this.getClass().getName()); } /* * Below method returns the dependencies for the passed in query to EXPLAIN. * The dependencies are the set of input tables and partitions, and are * provided back as JSON output for the EXPLAIN command. * Example output: * {"input_tables":[{"tablename": "default@test_sambavi_v1", "tabletype": "TABLE"}], * "input partitions":["default@srcpart@ds=2008-04-08/hr=11"]} */ @VisibleForTesting static JSONObject getJSONDependencies(ExplainWork work) throws Exception { assert(work.getDependency()); JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); JSONArray inputTableInfo = new JSONArray(); JSONArray inputPartitionInfo = new JSONArray(); for (ReadEntity input: work.getInputs()) { switch (input.getType()) { case TABLE: Table table = input.getTable(); JSONObject tableInfo = new JSONObject(); tableInfo.put("tablename", table.getCompleteName()); tableInfo.put("tabletype", table.getTableType().toString()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { tableInfo.put("tableParents", input.getParents().toString()); } inputTableInfo.put(tableInfo); break; case PARTITION: JSONObject partitionInfo = new JSONObject(); partitionInfo.put("partitionName", input.getPartition().getCompleteName()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { partitionInfo.put("partitionParents", input.getParents().toString()); } inputPartitionInfo.put(partitionInfo); break; default: break; } } outJSONObject.put("input_tables", inputTableInfo); outJSONObject.put("input_partitions", inputPartitionInfo); return outJSONObject; } public JSONObject getJSONCBOPlan(PrintStream out, ExplainWork work) throws Exception { JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); String cboPlan = work.getCboPlan(); if (cboPlan != null) { if (jsonOutput) { outJSONObject.put("CBOPlan", cboPlan); } else { out.println("CBO PLAN:"); out.println(cboPlan); } } return outJSONObject; } public JSONObject getJSONLogicalPlan(PrintStream out, ExplainWork work) throws Exception { isLogical = true; JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } if (work.getParseContext() != null) { if (out != null) { out.print("LOGICAL PLAN:"); } JSONObject jsonPlan = outputMap(work.getParseContext().getTopOps(), true, out, work.getExtended(), jsonOutput, 0); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("LOGICAL PLAN", jsonPlan); } } else { System.err.println("No parse context!"); } return outJSONObject; } private static String trueCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS true"; private static String falseCondNameVectorizationEnabled = HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED.varname + " IS false"; @VisibleForTesting ImmutablePair outputPlanVectorization(PrintStream out, boolean jsonOutput) throws Exception { if (out != null) { out.println("PLAN VECTORIZATION:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; HiveConf hiveConf = queryState.getConf(); boolean isVectorizationEnabled = HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVE_VECTORIZATION_ENABLED); String isVectorizationEnabledCondName = (isVectorizationEnabled ? trueCondNameVectorizationEnabled : falseCondNameVectorizationEnabled); List isVectorizationEnabledCondList = Arrays.asList(isVectorizationEnabledCondName); if (out != null) { out.print(indentString(2)); out.print("enabled: "); out.println(isVectorizationEnabled); out.print(indentString(2)); if (!isVectorizationEnabled) { out.print("enabledConditionsNotMet: "); } else { out.print("enabledConditionsMet: "); } out.println(isVectorizationEnabledCondList); } if (jsonOutput) { json.put("enabled", isVectorizationEnabled); JSONArray jsonArray = new JSONArray(Arrays.asList(isVectorizationEnabledCondName)); if (!isVectorizationEnabled) { json.put("enabledConditionsNotMet", jsonArray); } else { json.put("enabledConditionsMet", jsonArray); } } return new ImmutablePair(isVectorizationEnabled, jsonOutput ? json : null); } public JSONObject getJSONPlan(PrintStream out, ExplainWork work) throws Exception { return getJSONPlan(out, work.getRootTasks(), work.getFetchTask(), work.isFormatted(), work.getExtended(), work.isAppendTaskType(), work.getCboInfo(), work.getOptimizedSQL()); } public JSONObject getJSONPlan(PrintStream out, List> tasks, Task fetchTask, boolean jsonOutput, boolean isExtended, boolean appendTaskType, String cboInfo, String optimizedSQL) throws Exception { // If the user asked for a formatted output, dump the json output // in the output stream JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); if (jsonOutput) { out = null; } if (optimizedSQL != null) { if (jsonOutput) { outJSONObject.put("optimizedSQL", optimizedSQL); } else { out.print("OPTIMIZED SQL: "); out.println(optimizedSQL); } } List ordered = StageIDsRearranger.getExplainOrder(conf, tasks); if (fetchTask != null) { fetchTask.setParentTasks((List)StageIDsRearranger.getFetchSources(tasks)); if (fetchTask.getNumParent() == 0) { fetchTask.setRootTask(true); } ordered.add(fetchTask); } boolean suppressOthersForVectorization = false; if (this.work != null && this.work.isVectorization()) { ImmutablePair planVecPair = outputPlanVectorization(out, jsonOutput); if (this.work.isVectorizationOnly()) { // Suppress the STAGES if vectorization is off. suppressOthersForVectorization = !planVecPair.left; } if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("PLAN VECTORIZATION", planVecPair.right); } } if (!suppressOthersForVectorization) { JSONObject jsonDependencies = outputDependencies(out, jsonOutput, appendTaskType, ordered); if (out != null) { out.println(); } if (jsonOutput) { if (cboInfo != null) { outJSONObject.put("cboInfo", cboInfo); } outJSONObject.put(STAGE_DEPENDENCIES, jsonDependencies); } // Go over all the tasks and dump out the plans JSONObject jsonPlan = outputStagePlans(out, ordered, jsonOutput, isExtended); if (jsonOutput) { outJSONObject.put("STAGE PLANS", jsonPlan); } if (fetchTask != null) { fetchTask.setParentTasks(null); } } return jsonOutput ? outJSONObject : null; } private List toString(Collection objects) { List list = new ArrayList(); for (Object object : objects) { list.add(String.valueOf(object)); } return list; } private Object toJson(String header, String message, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return message; } out.print(header); out.println(": "); out.print(indentString(2)); out.println(message); return null; } private Object toJson(String header, List messages, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return new JSONArray(messages); } out.print(header); out.println(": "); for (String message : messages) { out.print(indentString(2)); out.print(message); out.println(); } return null; } private JSONObject getLocks(PrintStream out, ExplainWork work) { JSONObject jsonObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } List lockComponents = AcidUtils.makeLockComponents(work.getOutputs(), work.getInputs(), conf); if (null != out) { out.print("LOCK INFORMATION:\n"); } List locks = new ArrayList<>(lockComponents.size()); for (LockComponent component : lockComponents) { ExplainLockDesc lockDesc = new ExplainLockDesc(component); if (null != out) { out.print(lockDesc.getFullName()); out.print(" -> "); out.print(lockDesc.getLockType()); out.print('\n'); } else { locks.add(lockDesc); } } if (jsonOutput) { jsonObject.put("LOCK INFORMATION:", locks); } return jsonObject; } @Override public int execute(DriverContext driverContext) { PrintStream out = null; try { Path resFile = work.getResFile(); OutputStream outS = resFile.getFileSystem(conf).create(resFile); out = new PrintStream(outS); if (work.isCbo()) { JSONObject jsonCBOPlan = getJSONCBOPlan(out, work); if (work.isFormatted()) { out.print(jsonCBOPlan); } } else if (work.isLogical()) { JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work); if (work.isFormatted()) { out.print(jsonLogicalPlan); } } else if (work.isAuthorize()) { JSONObject jsonAuth = collectAuthRelatedEntities(out, work); if (work.isFormatted()) { out.print(jsonAuth); } } else if (work.getDependency()) { JSONObject jsonDependencies = getJSONDependencies(work); out.print(jsonDependencies); } else if (work.isLocks()) { JSONObject jsonLocks = getLocks(out, work); if(work.isFormatted()) { out.print(jsonLocks); } } else if (work.isAst()) { // Print out the parse AST if (work.getAstStringTree() != null) { outputAST(work.getAstStringTree(), out, work.isFormatted(), 0); } } else { if (work.isUserLevelExplain()) { // Because of the implementation of the JsonParserFactory, we are sure // that we can get a TezJsonParser. JsonParser jsonParser = JsonParserFactory.getParser(conf); work.getConfig().setFormatted(true); JSONObject jsonPlan = getJSONPlan(out, work); if (work.getCboInfo() != null) { jsonPlan.put("cboInfo", work.getCboInfo()); } try { jsonParser.print(jsonPlan, out); } catch (Exception e) { // if there is anything wrong happen, we bail out. LOG.error("Running explain user level has problem." + " Falling back to normal explain.", e); work.getConfig().setFormatted(false); work.getConfig().setUserLevelExplain(false); jsonPlan = getJSONPlan(out, work); } } else { JSONObject jsonPlan = getJSONPlan(out, work); if (work.isFormatted()) { // use the parser to get the output operators of RS JsonParser jsonParser = JsonParserFactory.getParser(conf); if (jsonParser != null) { jsonParser.print(jsonPlan, null); LOG.info("JsonPlan is augmented to {}", jsonPlan); } out.print(jsonPlan); } } } out.close(); out = null; return (0); } catch (Exception e) { LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e)); setException(e); return (1); } finally { IOUtils.closeStream(out); } } @VisibleForTesting JSONObject collectAuthRelatedEntities(PrintStream out, ExplainWork work) throws Exception { BaseSemanticAnalyzer analyzer = work.getAnalyzer(); HiveOperation operation = queryState.getHiveOperation(); JSONObject object = new JSONObject(new LinkedHashMap<>()); Object jsonInput = toJson("INPUTS", toString(analyzer.getInputs()), out, work); if (work.isFormatted()) { object.put("INPUTS", jsonInput); } Object jsonOutput = toJson("OUTPUTS", toString(analyzer.getOutputs()), out, work); if (work.isFormatted()) { object.put("OUTPUTS", jsonOutput); } String userName = SessionState.get().getAuthenticator().getUserName(); Object jsonUser = toJson("CURRENT_USER", userName, out, work); if (work.isFormatted()) { object.put("CURRENT_USER", jsonUser); } Object jsonOperation = toJson("OPERATION", operation.name(), out, work); if (work.isFormatted()) { object.put("OPERATION", jsonOperation); } if (analyzer.skipAuthorization()) { return object; } final List exceptions = new ArrayList(); Object delegate = SessionState.get().getActiveAuthorizer(); if (delegate != null) { Class itface = SessionState.get().getAuthorizerInterface(); Object authorizer = AuthorizationFactory.create(delegate, itface, new AuthorizationFactory.AuthorizationExceptionHandler() { @Override public void exception(Exception exception) { exceptions.add(exception.getMessage()); } }); SessionState.get().setActiveAuthorizer(authorizer); try { Driver.doAuthorization(queryState.getHiveOperation(), analyzer, ""); } finally { SessionState.get().setActiveAuthorizer(delegate); } } if (!exceptions.isEmpty()) { Object jsonFails = toJson("AUTHORIZATION_FAILURES", exceptions, out, work); if (work.isFormatted()) { object.put("AUTHORIZATION_FAILURES", jsonFails); } } return object; } private static String indentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.append(" "); } return sb.toString(); } @VisibleForTesting JSONObject outputMap(Map mp, boolean hasHeader, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { TreeMap tree = getBasictypeKeyedMap(mp); JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null && hasHeader && !mp.isEmpty()) { out.println(); } for (Entry ent : tree.entrySet()) { // Print the key if (out != null) { out.print(indentString(indent)); out.print(ent.getKey()); out.print(" "); } // Print the value if (isPrintable(ent.getValue())) { if (out != null) { out.print(ent.getValue()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() instanceof List) { if (ent.getValue() != null && !((List)ent.getValue()).isEmpty() && ((List)ent.getValue()).get(0) != null && ((List)ent.getValue()).get(0) instanceof TezWork.Dependency) { if (out != null) { boolean isFirst = true; for (TezWork.Dependency dep: (List)ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getType()); out.print(")"); } out.println(); } if (jsonOutput) { for (TezWork.Dependency dep: (List)ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getType()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else if (ent.getValue() != null && !((List) ent.getValue()).isEmpty() && ((List) ent.getValue()).get(0) != null && ((List) ent.getValue()).get(0) instanceof SparkWork.Dependency) { if (out != null) { boolean isFirst = true; for (SparkWork.Dependency dep: (List) ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getShuffleType()); out.print(", "); out.print(dep.getNumPartitions()); out.print(")"); } out.println(); } if (jsonOutput) { for (SparkWork.Dependency dep: (List) ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getShuffleType()); jsonDep.put("partitions", dep.getNumPartitions()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } } else if (ent.getValue() instanceof Map) { String stringValue = getBasictypeKeyedMap((Map)ent.getValue()).toString(); if (out != null) { out.print(stringValue); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), stringValue); } } else if (ent.getValue() != null) { if (out != null) { out.println(); } JSONObject jsonOut = outputPlan(ent.getValue(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (jsonOutput) { json.put(ent.getKey().toString(), jsonOut); } } else { if (out != null) { out.println(); } } } return jsonOutput ? json : null; } /** * Retruns a map which have either primitive or string keys. * * This is neccessary to discard object level comparators which may sort the objects based on some non-trivial logic. * * @param mp * @return */ private TreeMap getBasictypeKeyedMap(Map mp) { TreeMap ret = new TreeMap(); if (mp.size() > 0) { Object firstKey = mp.keySet().iterator().next(); if (firstKey.getClass().isPrimitive() || firstKey instanceof String) { // keep it as-is ret.putAll(mp); return ret; } else { for (Entry entry : mp.entrySet()) { // discard possibly type related sorting order and replace with alphabetical ret.put(entry.getKey().toString(), entry.getValue()); } } } return ret; } private JSONArray outputList(List l, PrintStream out, boolean hasHeader, boolean extended, boolean jsonOutput, int indent, boolean inTest) throws Exception { boolean first_el = true; boolean nl = false; JSONArray outputArray = new JSONArray(); for (Object o : l) { if (isPrintable(o)) { String delim = first_el ? " " : ", "; if (out != null) { out.print(delim); out.print(o); } if (jsonOutput) { outputArray.put(o); } nl = true; } else { if (first_el && (out != null) && hasHeader) { out.println(); } JSONObject jsonOut = outputPlan(o, out, extended, jsonOutput, jsonOutput ? 0 : (hasHeader ? indent + 2 : indent), "", inTest); if (jsonOutput) { outputArray.put(jsonOut); } } first_el = false; } if (nl && (out != null)) { out.println(); } return jsonOutput ? outputArray : null; } private boolean isPrintable(Object val) { if (val instanceof Boolean || val instanceof String || val instanceof Integer || val instanceof Long || val instanceof Byte || val instanceof Float || val instanceof Double || val instanceof Path) { return true; } if (val != null && val.getClass().isPrimitive()) { return true; } return false; } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, ""); } private boolean isInvokeVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // The EXPLAIN VECTORIZATION option was specified. final boolean desireOnly = this.work.isVectorizationOnly(); final VectorizationDetailLevel desiredVecDetailLevel = this.work.isVectorizationDetailLevel(); switch (vectorization) { case NON_VECTORIZED: // Display all non-vectorized leaf objects unless ONLY. if (desireOnly) { invokeFlag = false; } break; case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: if (vectorization.rank < desiredVecDetailLevel.rank) { // This detail not desired. invokeFlag = false; } break; case SUMMARY_PATH: case OPERATOR_PATH: if (desireOnly) { if (vectorization.rank < desiredVecDetailLevel.rank) { // Suppress headers and all objects below. invokeFlag = false; } } break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } private boolean isInvokeNonVectorization(Vectorization vectorization) { boolean invokeFlag = true; // Assume. // Do not display vectorization objects. switch (vectorization) { case SUMMARY: case OPERATOR: case EXPRESSION: case DETAIL: invokeFlag = false; break; case NON_VECTORIZED: // No action. break; case SUMMARY_PATH: case OPERATOR_PATH: // Always include headers since they contain non-vectorized objects, too. break; default: throw new RuntimeException("Unknown EXPLAIN vectorization " + vectorization); } return invokeFlag; } @VisibleForTesting JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, appendToHeader, queryState.getConf().getBoolVar(ConfVars.HIVE_IN_TEST)); } public JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader, boolean inTest) throws Exception { // Check if work has an explain annotation Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class); String keyJSONObject = null; if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } if (invokeFlag) { keyJSONObject = xpl_note.displayName(); if (out != null) { out.print(indentString(indent)); if (appendToHeader != null && !appendToHeader.isEmpty()) { out.println(xpl_note.displayName() + appendToHeader); } else { out.println(xpl_note.displayName()); } } } } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; // If this is an operator then we need to call the plan generation on the // conf and then the children if (work instanceof Operator) { Operator operator = (Operator) work; if (operator.getConf() != null) { String appender = isLogical ? " (" + operator.getOperatorId() + ")" : ""; JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput, jsonOutput ? 0 : indent, appender, inTest); if (this.work != null && (this.work.isUserLevelExplain() || this.work.isFormatted())) { if (jsonOut != null && jsonOut.length() > 0) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:", operator.getOperatorId()); } if (!this.work.isUserLevelExplain() && this.work.isFormatted() && operator.getConf() instanceof ReduceSinkDesc ) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("outputname:", ((ReduceSinkDesc) operator.getConf()).getOutputName()); } } if (jsonOutput) { json = jsonOut; } } if (!visitedOps.contains(operator) || !isLogical) { visitedOps.add(operator); if (operator.getChildOperators() != null) { int cindent = jsonOutput ? 0 : indent + 2; for (Operator op : operator.getChildOperators()) { JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent, "", inTest); if (jsonOutput) { ((JSONObject)json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut); } } } } if (jsonOutput) { return json; } return null; } // We look at all methods that generate values for explain Method[] methods = work.getClass().getMethods(); Arrays.sort(methods, new MethodComparator()); for (Method m : methods) { int prop_indents = jsonOutput ? 0 : indent + 2; note = AnnotationUtils.getAnnotation(m, Explain.class); if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()) || (this.work != null && this.work.isDebug() && Level.DEBUG.in(xpl_note.explainLevels())); } } if (invokeFlag) { Vectorization vectorization = xpl_note.vectorization(); if (invokeFlag) { if (this.work != null && this.work.isVectorization()) { invokeFlag = isInvokeVectorization(vectorization); } else { invokeFlag = isInvokeNonVectorization(vectorization); } } } if (invokeFlag) { Object val = null; try { if(postProcess(xpl_note)) { val = m.invoke(work, inTest); } else{ val = m.invoke(work); } } catch (InvocationTargetException ex) { // Ignore the exception, this may be caused by external jars val = null; } if (val == null) { continue; } if(xpl_note.jsonOnly() && !jsonOutput) { continue; } String header = null; boolean skipHeader = xpl_note.skipHeader(); boolean emptyHeader = false; if (!xpl_note.displayName().equals("")) { header = indentString(prop_indents) + xpl_note.displayName() + ":"; } else { emptyHeader = true; prop_indents = indent; header = indentString(prop_indents); } // Try the output as a primitive object if (isPrintable(val)) { if (out != null && shouldPrint(xpl_note, val)) { if (!skipHeader) { out.print(header); out.print(" "); } out.println(val); } if (jsonOutput && shouldPrint(xpl_note, val)) { json.put(header, val.toString()); } continue; } int ind = 0; if (!jsonOutput) { if (!skipHeader) { ind = prop_indents + 2; } else { ind = indent; } } // Try this as a map if (val instanceof Map) { // Go through the map and print out the stuff Map mp = (Map) val; if (out != null && !skipHeader && mp != null && !mp.isEmpty()) { out.print(header); } JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput, ind); if (jsonOutput && !mp.isEmpty()) { json.put(header, jsonOut); } continue; } // Try this as a list if (val instanceof List || val instanceof Set) { List l = val instanceof List ? (List)val : new ArrayList((Set)val); if (out != null && !skipHeader && l != null && !l.isEmpty()) { out.print(header); } JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput, ind, inTest); if (jsonOutput && !l.isEmpty()) { json.put(header, jsonOut); } continue; } // Finally check if it is serializable try { if (!skipHeader && out != null) { out.println(header); } JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind, "", inTest); if (jsonOutput && jsonOut != null && jsonOut.length() != 0) { if (!skipHeader) { json.put(header, jsonOut); } else { for(String k: JSONObject.getNames(jsonOut)) { json.put(k, jsonOut.get(k)); } } } continue; } catch (ClassCastException ce) { // Ignore } } } } if (jsonOutput) { if (keyJSONObject != null) { JSONObject ret = new JSONObject(new LinkedHashMap<>()); ret.put(keyJSONObject, json); return ret; } return json; } return null; } /** * use case: this is only use for testing purposes. For instance, we might * want to sort the expressions in a filter so we get deterministic comparable * golden files */ private boolean postProcess(Explain exp) { return exp.postProcess(); } /** * use case: we want to print the object in explain only if it is true * how to do : print it unless the following 3 are all true: * 1. displayOnlyOnTrue tag is on * 2. object is boolean * 3. object is false * @param exp * @param val * @return */ private boolean shouldPrint(Explain exp, Object val) { if (exp.displayOnlyOnTrue() && (val instanceof Boolean) & !((Boolean)val)) { return false; } return true; } private JSONObject outputPlan(Task task, PrintStream out, JSONObject parentJSON, boolean extended, boolean jsonOutput, int indent) throws Exception { if (out != null) { out.print(indentString(indent)); out.print("Stage: "); out.print(task.getId()); out.print("\n"); } // Start by getting the work part of the task and call the output plan for // the work JSONObject jsonOutputPlan = outputPlan(task.getWork(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (out != null) { out.println(); } if (jsonOutput) { parentJSON.put(task.getId(), jsonOutputPlan); } return null; } @VisibleForTesting JSONObject outputDependencies(Task task, PrintStream out, JSONObject parentJson, boolean jsonOutput, boolean taskType, int indent) throws Exception { boolean first = true; JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null) { out.print(indentString(indent)); out.print(task.getId()); } if ((task.getParentTasks() == null || task.getParentTasks().isEmpty())) { if (task.isRootTask()) { if (out != null) { out.print(" is a root stage"); } if (jsonOutput) { json.put("ROOT STAGE", "TRUE"); } } } else { StringBuilder s = new StringBuilder(); first = true; for (Task parent : task.getParentTasks()) { if (!first) { s.append(", "); } first = false; s.append(parent.getId()); } if (out != null) { out.print(" depends on stages: "); out.print(s.toString()); } if (jsonOutput) { json.put("DEPENDENT STAGES", s.toString()); } } Task currBackupTask = task.getBackupTask(); if (currBackupTask != null) { if (out != null) { out.print(" has a backup stage: "); out.print(currBackupTask.getId()); } if (jsonOutput) { json.put("BACKUP STAGE", currBackupTask.getId()); } } if (task instanceof ConditionalTask && ((ConditionalTask) task).getListTasks() != null) { StringBuilder s = new StringBuilder(); first = true; for (Task con : ((ConditionalTask) task).getListTasks()) { if (!first) { s.append(", "); } first = false; s.append(con.getId()); } if (out != null) { out.print(" , consists of "); out.print(s.toString()); } if (jsonOutput) { json.put("CONDITIONAL CHILD TASKS", s.toString()); } } if (taskType) { if (out != null) { out.print(" ["); out.print(task.getType()); out.print("]"); } if (jsonOutput) { json.put("TASK TYPE", task.getType().name()); } } if (out != null) { out.println(); } return jsonOutput ? json : null; } public String outputAST(String treeString, PrintStream out, boolean jsonOutput, int indent) throws JSONException { if (out != null) { out.print(indentString(indent)); out.println("ABSTRACT SYNTAX TREE:"); out.print(indentString(indent + 2)); out.println(treeString); } return jsonOutput ? treeString : null; } public JSONObject outputDependencies(PrintStream out, boolean jsonOutput, boolean appendTaskType, List tasks) throws Exception { if (out != null) { out.println(STAGE_DEPENDENCIES + ":"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { JSONObject jsonOut = outputDependencies(task, out, json, jsonOutput, appendTaskType, 2); if (jsonOutput && jsonOut != null) { json.put(task.getId(), jsonOut); } } return jsonOutput ? json : null; } public JSONObject outputStagePlans(PrintStream out, List tasks, boolean jsonOutput, boolean isExtended) throws Exception { if (out != null) { out.println("STAGE PLANS:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { outputPlan(task, out, json, isExtended, jsonOutput, 2); } return jsonOutput ? json : null; } /** * MethodComparator. * */ public class MethodComparator implements Comparator { @Override public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } } @Override public StageType getType() { return StageType.EXPLAIN; } @Override public String getName() { return "EXPLAIN"; } public static List getResultSchema() { FieldSchema tmpFieldSchema = new FieldSchema(); List colList = new ArrayList(); tmpFieldSchema.setName(EXPL_COLUMN_NAME); tmpFieldSchema.setType(STRING_TYPE_NAME); colList.add(tmpFieldSchema); return colList; } @Override public boolean canExecuteInParallel() { return false; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 14844 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/ExplainTask.java/#L84-L1302 | 2 | 2563 | 14844 | major |
| 2271 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13766 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 2 | 2271 | 13766 | minor |
| 907 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Long parameter list 5. Inappropriate intimacy 6. Indecent exposure | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
blob | Long method 2 Feature envy 3 Duplicated code 4 Long parameter list 5 Inappropriate intimacy 6 Indecent exposure | t | f | f | . Long method 2. Feature envy 3. Duplicated code 4. Long parameter list 5. Inappropriate intimacy 6. Indecent exposure | blob | 0 | 8199 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 2 | 907 | 8199 | minor |
| 419 | { "response": "YES I found bad smells", "detected_bad_smells": { "1": "Long Method", "2": "Data Class" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BeamIntersectRel extends Intersect implements BeamRelNode { public BeamIntersectRel( RelOptCluster cluster, RelTraitSet traits, List inputs, boolean all) { super(cluster, traits, inputs, all); } @Override public SetOp copy(RelTraitSet traitSet, List inputs, boolean all) { return new BeamIntersectRel(getCluster(), traitSet, inputs, all); } @Override public PTransform, PCollection> buildPTransform() { return new BeamSetOperatorRelBase(this, BeamSetOperatorRelBase.OpType.INTERSECT, all); } } |
blob | 1: long method, 2: data class | t | t | f | 1: long method, 2: data class | blob | 0 | 4239 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamIntersectRel.java/#L37-L52 | 1 | 419 | 4239 | minor |
| 375 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LogUtils { private static final String HIVE_L4J = "metastore-log4j2.properties"; private static final Logger l4j = LoggerFactory.getLogger(LogUtils.class); @SuppressWarnings("serial") public static class LogInitializationException extends Exception { LogInitializationException(String msg) { super(msg); } } /** * This is an exception that can be passed to logger just for printing the stacktrace. */ public static class StackTraceLogger extends Exception { public StackTraceLogger(final String msg) { super(msg); } } /** * Initialize log4j. * * @return an message suitable for display to the user * @throws LogInitializationException if log4j fails to initialize correctly */ public static String initHiveLog4j(Configuration conf) throws LogInitializationException { return initHiveLog4jCommon(conf, MetastoreConf.ConfVars.LOG4J_FILE); } private static String initHiveLog4jCommon(Configuration conf, ConfVars confVarName) throws LogInitializationException { if (MetastoreConf.getVar(conf, confVarName).equals("")) { // if log4j configuration file not set, or could not found, use default setting return initHiveLog4jDefault(conf, "", confVarName); } else { // if log4j configuration file found successfully, use HiveConf property value String log4jFileName = MetastoreConf.getVar(conf, confVarName); File log4jConfigFile = new File(log4jFileName); boolean fileExists = log4jConfigFile.exists(); if (!fileExists) { // if property specified file not found in local file system // use default setting return initHiveLog4jDefault( conf, "Not able to find conf file: " + log4jConfigFile, confVarName); } else { // property speficied file found in local file system // use the specified file final boolean async = checkAndSetAsyncLogging(conf); // required for MDC based routing appender so that child threads can inherit the MDC context System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, log4jFileName); logConfigLocation(); return "Logging initialized using configuration in " + log4jConfigFile + " Async: " + async; } } } private static boolean checkAndSetAsyncLogging(final Configuration conf) { final boolean asyncLogging = MetastoreConf.getBoolVar(conf, ConfVars.ASYNC_LOG_ENABLED); if (asyncLogging) { System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); // default is ClassLoaderContextSelector which is created during automatic logging // initialization in a static initialization block. // Changing ContextSelector at runtime requires creating new context factory which will // internally create new context selector based on system property. LogManager.setFactory(new Log4jContextFactory()); } return asyncLogging; } private static String initHiveLog4jDefault(Configuration conf, String logMessage, ConfVars confVarName) throws LogInitializationException { URL hive_l4j = null; switch (confVarName) { case LOG4J_FILE: hive_l4j = LogUtils.class.getClassLoader().getResource(HIVE_L4J); break; default: break; } if (hive_l4j != null) { final boolean async = checkAndSetAsyncLogging(conf); System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); Configurator.initialize(null, hive_l4j.toString()); logConfigLocation(); return (logMessage + "\n" + "Logging initialized using configuration in " + hive_l4j + " Async: " + async); } else { throw new LogInitializationException( logMessage + "Unable to initialize logging using " + LogUtils.HIVE_L4J + ", not found on CLASSPATH!"); } } private static void logConfigLocation() throws LogInitializationException { // Log a warning if hive-default.xml is found on the classpath if (MetastoreConf.getHiveDefaultLocation() != null) { l4j.warn("DEPRECATED: Ignoring hive-default.xml found on the CLASSPATH at " + MetastoreConf.getHiveDefaultLocation().getPath()); } // Look for hive-site.xml on the CLASSPATH and log its location if found. if (MetastoreConf.getHiveSiteLocation() == null) { l4j.warn("hive-site.xml not found on CLASSPATH"); } else { l4j.debug("Using hive-site.xml found on CLASSPATH at " + MetastoreConf.getHiveSiteLocation().getPath()); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 3872 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/LogUtils.java/#L37-L149 | 2 | 375 | 3872 | minor |
| 102 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1315 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 2 | 102 | 1315 | minor |
| 3920 | YES I found bad smells the bad smells are: 1.Short class, 2.Empty catch clause, 3. Meaningless class name, 4. Inappropriate inheritance, 5. Feature envy, 6. Inappropriate method name | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Short class,2Empty catch clause, 3 Meaningless class name, 4 Inappropriate inheritance,5 Feature envy, 6 Inappropriate method name | t | f | f | .Short class, 2.Empty catch clause, 3. Meaningless class name, 4. Inappropriate inheritance, 5. Feature envy, 6. Inappropriate method name | data class | 0 | 10262 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 3920 | 10262 | major |
| 380 | YES I found bad smells the bad smells are: 1. Feature envy 2. Feature envy 3. Feature envy 4. Feature envy 5. Feature envy 6. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | Feature envy2 Feature envy3 Feature envy4 Feature envy5 Feature envy6 Long method | t | f | f | . Feature envy2. Feature envy3. Feature envy4. Feature envy5. Feature envy6. Long method | data class | 0 | 3907 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 2 | 380 | 3907 | major |
| 2265 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 13729 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 2265 | 13729 | major |
| 893 | {"message":"YES I found bad smells","bad smells are":["Long Method","Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeleteIndexAction implements ExpirationAction { private static final Logger logger = LoggerFactory.getLogger(DeleteIndexAction.class); private final PersistentProvenanceRepository repository; private final IndexConfiguration indexConfiguration; private final IndexManager indexManager; public DeleteIndexAction(final PersistentProvenanceRepository repo, final IndexConfiguration indexConfiguration, final IndexManager indexManager) { this.repository = repo; this.indexConfiguration = indexConfiguration; this.indexManager = indexManager; } @Override public File execute(final File expiredFile) throws IOException { // count the number of records and determine the max event id that we are deleting. final long numDeleted = 0; long maxEventId = -1L; try (final RecordReader reader = RecordReaders.newRecordReader(expiredFile, repository.getAllLogFiles(), Integer.MAX_VALUE)) { maxEventId = reader.getMaxEventId(); } catch (final IOException ioe) { logger.warn("Failed to obtain max ID present in journal file {}", expiredFile.getAbsolutePath()); } // remove the records from the index final List indexDirs = indexConfiguration.getIndexDirectories(expiredFile); for (final File indexingDirectory : indexDirs) { final Term term = new Term(FieldNames.STORAGE_FILENAME, LuceneUtil.substringBefore(expiredFile.getName(), ".")); boolean deleteDir = false; final EventIndexWriter writer = indexManager.borrowIndexWriter(indexingDirectory); try { final IndexWriter indexWriter = writer.getIndexWriter(); indexWriter.deleteDocuments(term); indexWriter.commit(); final int docsLeft = indexWriter.numDocs(); deleteDir = docsLeft <= 0; logger.debug("After expiring {}, there are {} docs left for index {}", expiredFile, docsLeft, indexingDirectory); } finally { indexManager.returnIndexWriter(writer); } // we've confirmed that all documents have been removed. Delete the index directory. if (deleteDir) { indexManager.removeIndex(indexingDirectory); indexConfiguration.removeIndexDirectory(indexingDirectory); deleteDirectory(indexingDirectory); logger.info("Removed empty index directory {}", indexingDirectory); } } // Update the minimum index to 1 more than the max Event ID in this file. if (maxEventId > -1L) { indexConfiguration.setMinIdIndexed(maxEventId + 1L); } logger.info("Deleted Indices for Expired Provenance File {} from {} index files; {} documents removed", expiredFile, indexDirs.size(), numDeleted); return expiredFile; } private void deleteDirectory(final File dir) { if (dir == null || !dir.exists()) { return; } final File[] children = dir.listFiles(); if (children == null) { return; } for (final File child : children) { if (child.isDirectory()) { deleteDirectory(child); } else if (!child.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", child.getAbsolutePath()); } } if (!dir.delete()) { logger.warn("Unable to remove index directory {}; this directory should be cleaned up manually", dir); } } @Override public boolean hasBeenPerformed(final File expiredFile) throws IOException { return false; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 8108 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-provenance-repository-bundle/nifi-persistent-provenance-repository/src/main/java/org/apache/nifi/provenance/lucene/DeleteIndexAction.java/#L34-L122 | 1 | 893 | 8108 | major |
| 2371 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14308 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 2 | 2371 | 14308 | minor |
| 5585 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 9277 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5585 | 9277 | major |
| 1444 | YES, I found bad smells. 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10980 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 2 | 1444 | 10980 | major |
| 1888 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12300 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 1 | 1888 | 12300 | critical |
| 4167 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 10969 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 4167 | 10969 | minor |
| 601 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 5994 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 1 | 601 | 5994 | minor |
| 3904 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10221 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 2 | 3904 | 10221 | minor |
| 854 | YES I found bad smells the bad smells are: 1. Feature envy: The simpleMethodsRequiringTesting() method is using operations from the IntermediateModel class, which belongs to a different class. 2. Long method: The loadDefaultFileHeader() method is longer than 10 lines, making it harder to read and maintain. 3. Long parameter list: The IntermediateModel constructor has 9 parameters, which is considered a large number and may make the code harder to understand. 4. Magic numbers: The getCopyrightDateRange() method uses the number 5 without any explanation, which could be considered a magic number. 5. Inconsistent formatting: Some lines, such as the ones in the getResponseMetadataClassName() method, are not properly indented, making the code less readable. 6. Too many public methods: This class has multiple public methods, which may lead to potential security and maintainability issues. 7. Mix of different responsibilities: This class is responsible for handling and managing multiple different types of data, such as operations, shapes, and examples. This can make it harder to understand and maintain the code. 8. Lack of comments or documentation: The code lacks proper comments or documentation, making it harder to understand the purpose of each method. 9. Unused variables: The endpointOperation and namingStrategy variables are never used in the class. This indicates that the code may not have been properly reviewed or refactored. 10. Method complexity: The containsRequestSigners() and containsRequestEventStreams() methods have complex logic and could benefit from being split into smaller, more understandable methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
blob | Feature envy: The simpleMethodsRequiringTesting() method is using operations from the IntermediateModel class, which belongs to a different class2 Long method: The loadDefaultFileHeader() method is longer than | t | f | f | . Feature envy: The simpleMethodsRequiringTesting() method is using operations from the IntermediateModel class, which belongs to a different class.2. Long method: The loadDefaultFileHeader() method is longer than | blob | 0 | 7878 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 2 | 854 | 7878 | minor |
| 921 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
blob | long method | t | t | f | long method | blob | 0 | 8276 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 921 | 8276 | minor |
| 1667 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; private final AbstractPathConfiguration classpathConfiguration; private final ClassLoaderConfiguration classLoaderConfiguration; private final boolean isForkRequested; private final boolean isInForkedVm; public StartupConfiguration( @Nonnull String providerClassName, @Nonnull AbstractPathConfiguration classpathConfiguration, @Nonnull ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } public boolean isProviderMainClass() { return providerClassName.endsWith( "#main" ); } public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) { return new StartupConfiguration( providerClassName, classpathConfiguration, classLoaderConfiguration, true, true ); } public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } @Deprecated public boolean useSystemClassLoader() { // todo; I am not totally convinced this logic is as simple as it could be return classLoaderConfiguration.isUseSystemClassLoader() && ( isInForkedVm || isForkRequested ); } public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } public String getProviderClassName() { return providerClassName; } public String getActualClassName() { return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; } /** * Strip any of a supplied String from the end of a String. * * If the strip String is {@code null}, whitespace is * stripped. * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ private static String stripEnd( String str, String strip ) { if ( str == null ) { return null; } int end = str.length(); if ( strip == null ) { while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) { end--; } } else { while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) { end--; } } return str.substring( 0, end ); } public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } public boolean isShadefire() { return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); } public void writeSurefireTestClasspathProperty() { getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 11625 | https://github.com/apache/maven-surefire/blob/e57f76c7e858dbbaac6be4cbcd16e215de10b064/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java/#L29-L140 | 2 | 1667 | 11625 | minor |
| 1236 | {"result":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EventAdapterGenerator { public static AdapterClassLoader ldr = new AdapterClassLoader(); static Class EVENTLISTENER = null; static String CLASSPACKAGE = "org/apache/bsf/util/event/adapters/"; static String WRITEDIRECTORY = null; // starting 8 bytes of all Java Class files static byte CLASSHEADER[]; // constant pool items found in all event adapters static short BASECPCOUNT; // number of cp items + 1 ( cp item # 0 reserved for JVM ) static byte BASECP[]; // // some bytes in the middle of the class file (see below) static byte FIXEDCLASSBYTES[]; // the initialization method, noargs constructor static byte INITMETHOD[]; private static BSF_Log logger=null; /* The static initializer */ static { // logger = LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); logger = BSF_LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); String USERCLASSPACKAGE = System.getProperty("DynamicEventClassPackage", ""); if (!USERCLASSPACKAGE.equals("")) { CLASSPACKAGE = USERCLASSPACKAGE; } if(CLASSPACKAGE.length() > 0 ) { CLASSPACKAGE = CLASSPACKAGE.replace('\\','/'); if(!CLASSPACKAGE.endsWith("/")) { CLASSPACKAGE = CLASSPACKAGE+"/"; } } WRITEDIRECTORY = System.getProperty("DynamicEventClassWriteDirectory",CLASSPACKAGE); if(WRITEDIRECTORY.length() > 0 ) { WRITEDIRECTORY = WRITEDIRECTORY.replace('\\','/'); if(!WRITEDIRECTORY.endsWith("/")) { WRITEDIRECTORY = WRITEDIRECTORY+"/"; } } try // { EVENTLISTENER = Class.forName("java.util.EventListener"); } { // EVENTLISTENER = Thread.currentThread().getContextClassLoader().loadClass ("java.util.EventListener"); // rgf, 2006-01-05 // rgf, 20070917: first try context class loader, then BSFManager's defining class loader EVENTLISTENER=null; ClassLoader tccl=Thread.currentThread().getContextClassLoader(); if (tccl!=null) { try { EVENTLISTENER = tccl.loadClass ("java.util.EventListener"); } catch(ClassNotFoundException ex01) {} } if (EVENTLISTENER==null) // did not work, try to load it via the definedClassLoader { EVENTLISTENER = BSFManager.getDefinedClassLoader().loadClass ("java.util.EventListener"); } } catch(ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // start of the Java Class File CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xCA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xFE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)3); // minor version CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)45); // major version // Start the constant pool for base items in all event adapter classes BASECPCOUNT = 17; // number of cp items + 1 ( cp item # 0 reserved for JVM ) // cp item 01 BASECP = Bytecode.addUtf8(BASECP,"()V"); // cp item 02 BASECP = Bytecode.addUtf8(BASECP,""); // cp item 03 BASECP = Bytecode.addUtf8(BASECP,"Code"); // cp item 04 BASECP = Bytecode.addUtf8(BASECP,"eventProcessor"); // cp item 05 BASECP = Bytecode.addUtf8(BASECP,"java/lang/Object"); // cp item 06 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventAdapterImpl"); // cp item 07 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventProcessor"); // cp item 08 BASECP = Bytecode.addUtf8(BASECP,"(Ljava/lang/String;[Ljava/lang/Object;)V"); // cp item 09 BASECP = Bytecode.addUtf8(BASECP,"Lorg/apache/bsf/util/event/EventProcessor;"); // cp item 10 BASECP = Bytecode.addClass(BASECP,(short)5); // Class "java/lang/Object" // cp item 11 BASECP = Bytecode.addClass(BASECP,(short)6); // Class "org/apache/bsf/util/event/EventAdapterImpl" // cp item 12 BASECP = Bytecode.addClass(BASECP,(short)7); // Class "org/apache/bsf/util/event/EventProcessor" // cp item 13 BASECP = Bytecode.addNameAndType(BASECP,(short)2,(short)1); // "" "()V" // cp item 14 BASECP = Bytecode.addNameAndType(BASECP,(short)4,(short)9); // "eventProcessor" "Lorg/apache/bsf/util/event/EventProcessor;" // cp item 15 BASECP = Bytecode.addFieldRef(BASECP,(short)11,(short)14); // cp item 16 BASECP = Bytecode.addMethodRef(BASECP,(short)11,(short)13); // fixed bytes in middle of class file FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0x21); // access_flags (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)20); // this_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)11); // super_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)1); // interface_count (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)19); // interfaces (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0); // field_count (fixed) // initialization method, constructor INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // access_flags INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)2); // name_index "" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // descriptor_index "()V" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // attribute_count INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)3); // attribute_name_index "Code" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)17); // attribute_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_stack INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_locals INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)5); // code_length //code INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0x2A); // aload_0 INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB7); // invokespecial INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)16); // method_ref index INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB1); // return // exception table INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // exception_table_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // attributes_count } /* methods that take an EventListener Class Type to create an EventAdapterClass */ public static Class makeEventAdapterClass(Class listenerType,boolean writeClassFile) { logger.debug("EventAdapterGenerator"); if( EVENTLISTENER.isAssignableFrom(listenerType) ) { boolean exceptionable = false; boolean nonExceptionable = false; byte constantPool[] = null; short cpBaseIndex; short cpCount = 0; short cpExceptionBaseIndex; short exceptionableCount; short nonExceptionableCount; /* Derive Names */ String listenerTypeName = listenerType.getName(); logger.debug("ListenerTypeName: "+listenerTypeName); String adapterClassName = CLASSPACKAGE+ (listenerTypeName.endsWith("Listener") ? listenerTypeName.substring(0, listenerTypeName.length() - 8) : listenerTypeName).replace('.', '_') + "Adapter"; String finalAdapterClassName = adapterClassName; Class cached = null; int suffixIndex = 0; do { if (null != (cached = ldr.getLoadedClass(finalAdapterClassName))) { logger.debug("cached: "+cached); try { if (!listenerType.isAssignableFrom(cached)) finalAdapterClassName = adapterClassName + "_" + suffixIndex++; else return cached; } catch(VerifyError ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); return cached; } } } while (cached != null); String eventListenerName = listenerTypeName.replace('.', '/'); /* method stuff */ java.lang.reflect.Method lms[] = listenerType.getMethods(); /* ****************************************************************************************** */ // Listener interface // Class name cpCount += 4; // cp item 17 constantPool = Bytecode.addUtf8(constantPool,eventListenerName); // cp item 18 constantPool = Bytecode.addUtf8(constantPool,finalAdapterClassName); // cp item 19 constantPool = Bytecode.addClass(constantPool,(short)17); // cp item 20 constantPool = Bytecode.addClass(constantPool,(short)18); // do we have nonExceptionalble event, exceptionable or both for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); if( 0 < exceptionTypes.length) { exceptionable = true; } else { nonExceptionable = true; } }/* End for*/ /* ****************************************************************************************** */ // optional inclusion of nonexceptional events affects exceptional events indices nonExceptionableCount = 0; if(nonExceptionable) { nonExceptionableCount = 3; cpCount += nonExceptionableCount; // cp item 21 constantPool = Bytecode.addUtf8(constantPool,"processEvent"); // cp item 22 constantPool = Bytecode.addNameAndType(constantPool,(short)21,(short)8); // cp item 23 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)22); } /* ****************************************************************************************** */ // optional inclusion of exceptional events affects CP Items which follow for specific methods exceptionableCount = 0; if(exceptionable) { int classIndex = BASECPCOUNT + cpCount + 1; int nameIndex = BASECPCOUNT + cpCount + 0; int natIndex = BASECPCOUNT + cpCount + 3; exceptionableCount = 5; cpCount += exceptionableCount; // cp item 24 or 21 constantPool = Bytecode.addUtf8(constantPool,"processExceptionableEvent"); // cp item 25 or 22 constantPool = Bytecode.addUtf8(constantPool,"java/lang/Exception"); // cp item 26 or 23 constantPool = Bytecode.addClass(constantPool,(short)classIndex); // cp item 27 or 24 constantPool = Bytecode.addNameAndType(constantPool,(short)nameIndex,(short)8); // cp item 28 or 25 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)natIndex); } // base index for method cp references cpBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpBaseIndex: " + cpBaseIndex); for (int i = 0 ; i < lms.length ; ++i) { String eventMethodName = lms[i].getName(); String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); cpCount += 3; // cp items for event methods constantPool = Bytecode.addUtf8(constantPool,eventMethodName); constantPool = Bytecode.addUtf8(constantPool,("(L" + eventName + ";)V")); constantPool = Bytecode.addString(constantPool,(short)(BASECPCOUNT+cpCount-3)); }/* End for*/ boolean propertyChangeFlag[] = new boolean[lms.length]; int cpIndexPCE = 0; for (int i = 0 ; i < lms.length ; ++i) { String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); // cp items for PropertyChangeEvent special handling if(eventName.equalsIgnoreCase("java/beans/PropertyChangeEvent")) { propertyChangeFlag[i] = true; if( 0 == cpIndexPCE ) { constantPool = Bytecode.addUtf8(constantPool,eventName); constantPool = Bytecode.addUtf8(constantPool,"getPropertyName"); constantPool = Bytecode.addUtf8(constantPool,"()Ljava/lang/String;"); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT + cpCount)); constantPool = Bytecode.addNameAndType(constantPool, (short)(BASECPCOUNT + cpCount + 1), (short)(BASECPCOUNT + cpCount + 2)); constantPool = Bytecode.addMethodRef(constantPool, (short)(BASECPCOUNT + cpCount + 3), (short)(BASECPCOUNT + cpCount + 4)); cpCount += 6; cpIndexPCE = BASECPCOUNT + cpCount - 1; } } else { propertyChangeFlag[i] = false; } }/* End for*/ cpExceptionBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpExceptionBaseIndex: " + cpExceptionBaseIndex); int excpIndex[][] = new int[lms.length][]; for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); excpIndex[i] = new int[exceptionTypes.length]; for ( int j = 0 ; j < exceptionTypes.length ; j++) { constantPool = Bytecode.addUtf8(constantPool,exceptionTypes[j].getName().replace('.', '/')); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT+cpCount)); excpIndex[i][j] = BASECPCOUNT + cpCount + 1; cpCount += 2; } }/* End for*/ /* end constant pool */ /* ************************************************************************************************ */ // put the Class byte array together /* start */ byte newClass[] = CLASSHEADER; // magic, version (fixed) short count = (short)(BASECPCOUNT + cpCount); newClass = ByteUtility.addBytes(newClass,count); // constant_pool_count (variable) newClass = ByteUtility.addBytes(newClass,BASECP); // constant_pool (fixed) newClass = ByteUtility.addBytes(newClass,constantPool); // constant_pool (variable) newClass = ByteUtility.addBytes(newClass,FIXEDCLASSBYTES); // see FIXEDCLASSBYTES (fixed) newClass = ByteUtility.addBytes(newClass,(short)(lms.length+1)); // method_count (variable) newClass = ByteUtility.addBytes(newClass,INITMETHOD); // constructor (fixed) // methods /* ****************************************************************************************** */ /* loop over listener methods from listenerType */ for (int i = 0 ; i < lms.length ; ++i) { newClass = ByteUtility.addBytes(newClass,(short)1); // access_flags (fixed) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+0)); // name_index (variable) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+1)); // descriptor_index (variable) newClass = ByteUtility.addBytes(newClass,(short)1); // attribute_count (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // attribute_name_index code(fixed) // Code Attribute Length int length = 32; if( 0 < excpIndex[i].length ) { length += 5 + 8 * ( 1 + excpIndex[i].length ); } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // attribute_length (variable) // start code attribute newClass = ByteUtility.addBytes(newClass,(short)6); // max_stack (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // max_locals (fixed) // Code Length length = 20; if(exceptionable && 0 < excpIndex[i].length) { length += 5; } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // code_length (variable) // start code newClass = ByteUtility.addBytes(newClass,(byte)0x2A); // aload_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB4); // getfield (fixed) newClass = ByteUtility.addBytes(newClass,(short)15); // index (fixed) if(propertyChangeFlag[i]) { // the propertyName is passed as the first parameter newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB6); // invokevirtual (fixed) newClass = ByteUtility.addBytes(newClass,(short)cpIndexPCE); // methodref (variable) } else { // the eventMethodName is passed as the first parameter // Target for method invocation. newClass = ByteUtility.addBytes(newClass,(byte)0x12); // ldc (fixed) newClass = ByteUtility.addBytes(newClass,(byte)(cpBaseIndex+3*i+2)); // index (byte) (variable) } newClass = ByteUtility.addBytes(newClass,(byte)0x04); // iconst_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBD); // anewarray (fixed) newClass = ByteUtility.addBytes(newClass,(short)10); // Class java/lang/Object (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x59); // dup (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x53); // aastore (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB9); // invokeinterface (fixed) // index to processEvent or processExceptionableEvent method length = 23; // actually an index into cp if(exceptionable && nonExceptionable) { // interface method index if( 0 < lms[i].getExceptionTypes().length ) { length += 5; } } else if(exceptionable) { length += 2; } newClass = ByteUtility.addBytes(newClass,(short)length); // index (process??????...) (variable) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x00); // noop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) if(exceptionable && 0 < excpIndex[i].length) { // exception code newClass = ByteUtility.addBytes(newClass,(byte)0x4D); // astore_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2C); // aload_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBF); // athrow (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x57); // pop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) // end code // exception table length = excpIndex[i].length; newClass = ByteUtility.addBytes(newClass,(short)(1+length)); // exception_table_length (variable) for( int j = 0 ; j < length ; j++ ) { // catch exception types and rethrow newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)22); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)20); // handler_pc (fixed) } newClass = ByteUtility.addBytes(newClass,(short)excpIndex[i][j]); // catch_type (variable) } // catch "exception" and trap it newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)25); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)23); // handler_pc (fixed) } if(nonExceptionable) { newClass = ByteUtility.addBytes(newClass,(short)26); } // catch_type (fixed) else // or { newClass = ByteUtility.addBytes(newClass,(short)23); } // catch_type (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)0); } // exception_table_length (fixed) // attributes on the code attribute (none) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) // end code attribute }/* End for*/ // Class Attributes (none for this) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) /* done */ logger.debug("adapterName: " + finalAdapterClassName); logger.debug("cpCount: " + count + " = " + BASECPCOUNT + " + " + cpCount); logger.debug("methodCount: " + (lms.length+1)); // output to disk class file /* ****************************************************************************************** */ // now create the class and load it // return the Class. if (writeClassFile) { try { // removed "WRITEDIRECTORY+", as this path is already part of 'finalAdapterClassName' FileOutputStream fos = new FileOutputStream(finalAdapterClassName+".class"); fos.write(newClass); fos.close(); } catch(IOException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { Class ret = ldr.loadClass(finalAdapterClassName); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } try { Class ret = ldr.defineClass(finalAdapterClassName,newClass); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch(Throwable ex) // rgf, 2012-01-15 { System.err.println(ex.getMessage()); ex.printStackTrace(); } } return null; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10389 | https://github.com/apache/commons-bsf/blob/88b2601a3caecc32aba38f2b3980d646e9a1b698/src/main/java/org/apache/bsf/util/event/generator/EventAdapterGenerator.java/#L46-L606 | 1 | 1236 | 10389 | major |
| 2162 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | long method | t | t | f | long method | blob | 0 | 13329 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 2162 | 13329 | major |
| 664 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 6459 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 664 | 6459 | minor |
| 22 | { "response": "YES I found bad smells the bad smells are: 1. Long method" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void hide() { view.close(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 686 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/progressor/ProgressMonitorPresenter.java/#L74-L76 | 2 | 22 | 686 | minor |
| 355 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 3668 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 355 | 3668 | major |
| 2167 | { "response": "YES I found bad smells", "the bad smells are:": [ "Long method", "Duplicate code" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | long method, duplicate code | t | t | f | long method, duplicate code | data class | 0 | 13349 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 2 | 2167 | 13349 | major |
| 1996 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Cel4rreg { long seghigh; long seglow; int p_dsafmt = -1; long p_dsaptr; RegisterSet regs; /** * Creates the instance and attempts to locate the registers. */ Cel4rreg() { /* Debug option - before we do anything else, try using the old svcdump code */ String useSvcdump = System.getProperty("zebedee.use.svcdump"); if (useSvcdump != null && useSvcdump.equals("true")) { getRegistersFromSvcdump(); return; } /* * Try and get the registers from the following locations: * * 1) RTM2 work area * 2) BPXGMSTA service * 3) linkage stack entries * 4) TCB * 5) Usta * * if any succeeds we return otherwise move to the next location. */ int whereCount = 0; try { if ((regs = getRegistersFromRTM2()) != null && whereCount++ >= whereSkip) { whereFound = "RTM2"; failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } /* If we still have not found a dsa, invoke kernel svs */ try { if ((regs = getRegistersFromBPXGMSTA()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (whereFound == null) whereFound = "BPXGMSTA"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { //throw new Error("oops: " + e); } try { if ((regs = getRegistersFromLinkageStack()) != null && whereCount++ >= whereSkip) { whereFound = "Linkage"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "Cel4rreg","Unexepected exception", e); throw new Error("Unexpected IOException: " + e); } try { if ((regs = getRegistersFromTCB()) != null && whereCount++ >= whereSkip) { whereFound = "TCB"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } try { if (is64bit) { /* This is from celqrreg.plx370: "Get the save R4 from a NOSTACK call" */ long lca = CeexlaaTemplate.getCeelaa_lca64(inputStream, laa); p_dsaptr = CeelcaTemplate.getCeelca_savstack(inputStream, lca); log.fine("p_dsaptr from lca = " + hex(p_dsaptr)); p_dsafmt = stackdirection = CEECAASTACK_DOWN; if (validateDSA() == 0 && whereCount++ >= whereSkip) { whereFound = "LCA"; return; } } } catch (IOException e) { throw new Error("oops: " + e); } /* Last ditch */ try { if ((regs = getRegistersFromUsta()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { } whereFound = "not found"; } /** * Try and get the registers from the RTM2 work area. Returns null if none found. As a * side-effect it also sets the stackdirection. */ private RegisterSet getRegistersFromRTM2() throws IOException { int level = ceecaalevel(); log.finer("caa level is " + level); /* If the CAA level is 13 or greater, get stack direction from * CAA. For older releases or the dummy CAA, default stack * direction to UP. */ if (is64bit) { /* Always use downstack in 64-bit mode? */ stackdirection = CEECAASTACK_DOWN; log.finer("stack direction is down"); } else if (level >= 13) { /* If LE 2.10 or higher */ /* Obtain dsa format from the CAA */ stackdirection = ceecaa_stackdirection(); log.finer("stack direction is " + (stackdirection == CEECAASTACK_UP ? "up" : "down")); } else { stackdirection = CEECAASTACK_UP; log.finer("stack direction is up"); } if ((stackdirection == CEECAASTACK_DOWN) && !is64bit) { try { long tempptr = ceecaasmcb(); //the ceecaasmcb call is not currently supported for 64 bit CAAs seghigh = SmcbTemplate.getSmcb_dsbos(inputStream, tempptr); seglow = CeexstkhTemplate.getStkh_stackfloor(inputStream, seghigh); } catch (Exception e) { //throw new Error("oops: " + e); return null; } } /* At this point, a valid CAA has been obtained. Access the RTM2 to obtain the DSA. */ long rtm2ptr = tcb.tcbrtwa(); if (rtm2ptr != 0) { try { log.finer("found some rtm2 registers"); RegisterSet regs = new RegisterSet(); long rtm2grs = rtm2ptr + Ihartm2aTemplate.getRtm2ereg$offset(); long rtm2grshi = rtm2ptr + Ihartm2aTemplate.getRtm2g64h$offset(); for (int i = 0; i < 16; i++) { long low = space.readUnsignedInt(rtm2grs + i*4); long high = is64bit ? space.readUnsignedInt(rtm2grshi + i*4) : 0; regs.setRegister(i, (high << 32) | low); } long rtm2psw = rtm2ptr + Ihartm2aTemplate.getRtm2apsw$offset(); regs.setPSW(space.readLong(rtm2psw)); if (registersValid(regs)) { log.finer("found good dsa in rtm2"); } else { log.finer("bad dsa in rtm2"); regs = null; } return regs; } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } } else { log.finer("failed to get registers from rtm2"); return null; } } /** * Validates the given register set with retry for down stack */ private boolean registersValid(RegisterSet regs) throws IOException { if (regs == null) return false; p_dsafmt = stackdirection; if (p_dsafmt == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } int lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } else { if (stackdirection == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 (again) = " + hex(p_dsaptr)); p_dsafmt = CEECAASTACK_UP; lastrc = validateDSA(); if (lastrc == WARNING) { lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } } } /* reset values */ log.finer("p_dsaptr invalid so reset: " + hex(p_dsaptr)); p_dsaptr = 0; } return false; } /** * Try and get the registers from the BPXGMSTA service. */ private RegisterSet getRegistersFromBPXGMSTA() throws IOException { RegisterSet regs = tcb.getRegistersFromBPXGMSTA(); if (is64bit) // celqrreg appears to always assume down stack stackdirection = CEECAASTACK_DOWN; if (registersValid(regs)) { log.finer("found good dsa in BPXGMSTA"); return regs; } else { log.finer("BPX registers are invalid so keep looking"); return null; } } /** * Try and get the registers from the linkage stack. */ private RegisterSet getRegistersFromLinkageStack() throws IOException { log.finer("enter getRegistersFromLinkageStack"); try { Lse[] linkageStack = tcb.getLinkageStack(); /* If Linkage stack is empty, leave */ if (linkageStack.length == 0) { log.finer("empty linkage stack"); return null; } for (int i = 0; i < linkageStack.length; i++) { Lse lse = linkageStack[i]; if (lse.lses1pasn() == space.getAsid()) { RegisterSet regs = new RegisterSet(); if (lse.isZArchitecture() && (lse.lses1typ7() == Lse.LSED1PC || lse.lses1typ7() == Lse.LSED1BAKR)) { log.finer("found some z arch registers"); regs.setPSW(lse.lses1pswh()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lses1grs(j)); } } else { log.finer("found some non z arch registers"); regs.setPSW(lse.lsespsw()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lsesgrs(j)); } } if (registersValid(regs)) { log.finer("found good dsa in linkage stack"); return regs; } } else { log.finer("different asid: " + hex(lse.lses1pasn())); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } log.finer("could not find registers in linkage stack"); return null; } /** * Try and get the registers from the TCB. */ private RegisterSet getRegistersFromTCB() throws IOException { log.finer("getRegistersFromTCB"); RegisterSet regs = tcb.getRegisters(); if (registersValid(regs)) { log.finer("found good dsa in TCB"); return regs; } else { return null; } } /** * Try and get the registers from the Usta. Note that this is a kind of last-ditch * thing and so no validation is done. */ private RegisterSet getRegistersFromUsta() throws IOException { log.fine("enter getRegistersFromUsta"); RegisterSet regs = tcb.getRegistersFromUsta(); if (registersValid(regs)) { log.finer("found good dsa in Usta"); return regs; } else { /* If there are more than three stack entries that's probably better than nothing */ boolean isDownStack = stackdirection == CEECAASTACK_DOWN; long dsaptr; if (isDownStack) { dsaptr = regs.getRegister(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { dsaptr = regs.getRegister(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } try { DsaStackFrame dsa = new DsaStackFrame(dsaptr, isDownStack, regs, space, Caa.this); int count = 0; for (; dsa != null; dsa = dsa.getParentFrame()) { if (++count > 3) { p_dsaptr = dsaptr; p_dsafmt = stackdirection; return regs; } } } catch (IOException e) { } catch (AssertionError e) { } } return null; } /** * Try and get the registers using the old svcdump code. This is for debugging * purposes only. Uses reflection so there is no compilation dependency. */ private void getRegistersFromSvcdump() { } /** * Validate the given DSA. Returns 0 if valid. Note because this is Java, we can't * modify the input parameters, so we use the instance variables instead and * val_dsa == p_dsaptr, val_dsafmt == p_dsafmt. */ private int validateDSA() { log.finer("attempt to validate " + hex(p_dsaptr) + " on " + (p_dsafmt == CEECAASTACK_DOWN ? "down" : "up") + " stack"); try { if (is64bit) { assert laa != 0; long l_sancptr = CeexlaaTemplate.getCeelaa_sanc64(inputStream, laa); assert l_sancptr != 0; long seghigh = CeexsancTemplate.getSanc_bos(inputStream, l_sancptr); long seglow = 0; long sanc_stack = CeexsancTemplate.getSanc_stack(inputStream, l_sancptr); long sanc_user_stack = CeexsancTemplate.getSanc_user_stack(inputStream, l_sancptr); if (sanc_stack == sanc_user_stack) { /* Get Stackfloor from sanc */ seglow = CeexsancTemplate.getSanc_user_floor(inputStream, l_sancptr); } else { /* Get StackFloor from LAA */ seglow = CeexlaaTemplate.getCeelaa_stackfloor64(inputStream, laa); } if (p_dsaptr < seghigh && (p_dsaptr + 0x800) >= seglow && (p_dsaptr & 0xf) == 0) { log.finer("dsa " + hex(p_dsaptr) + " is within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return 0; } else { log.finer("dsa " + hex(p_dsaptr) + " is NOT within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return ERROR; } } if (p_dsafmt == CEECAASTACK_DOWN) { /* the check for being in the current segment is commented out */ } else { if (is64bit) return ERROR; long tptr = ceecaaerrcm(); /* Chicken egg situation */ //assert !space.is64bit(); /* If the input DSA address is within the HCOM and double word aligned, * assume that it is good. */ if (p_dsaptr < (tptr + hcomLength) && p_dsaptr >= tptr && (p_dsaptr & 7) == 0) { log.finer("upstack dsa " + hex(p_dsaptr) + " is inside hcom"); return 0; } } long ddsa = ceecaaddsa(); long dsaptr = p_dsaptr; int dsafmt8 = p_dsafmt; long slowdsaptr = p_dsaptr; int slowdsafmt8 = p_dsafmt; for (boolean slow = false;; slow = !slow) { Ceexdsaf dsaf = new Ceexdsaf(space, dsaptr, dsafmt8, is64bit); /* If the stack direction is down but we are validating an upstack DSA * and the current DSA is inside the current segment of the down stack, * assume this must be a OS_NOSTACK call, return WARNING and replace * input DSA and DSAFmt with R4 value from this DSA */ log.finer("looping with dsa = " + hex(dsaptr)); if (stackdirection == CEECAASTACK_DOWN && p_dsafmt == CEECAASTACK_UP && dsaptr < seghigh && dsaptr >= seglow) { p_dsaptr = CeedsaTemplate.getCeedsar4(inputStream, dsaptr); p_dsafmt = CEECAASTACK_DOWN; log.finer("warning, try switching to down stack"); return WARNING; } long callers_dsaptr = dsaf.DSA_Prev; dsafmt8 = dsaf.DSA_Format; /* If we are not able to backchain any farther or we have encountered * a linkage stack, assume that the input DSA address is bad. */ if (callers_dsaptr == 0 || callers_dsaptr == F1SA) { log.finer("cannot backchain futher because " + (callers_dsaptr == 0 ? "zero" : "linkage stack") + " found"); return ERROR; } /* If we were able to backchain to the dummy DSA, the input DSA address * must be good. */ if (callers_dsaptr == ddsa) { log.finer("dummy dsa reached"); return 0; } /* If we backchained across a stack transition, assume that the input * DSA address is good. */ if (dsafmt8 != p_dsafmt) { log.finer("backchained across a stack transition"); return 0; } /* If we have located an upstack DSA with a valid NAB value, assume that * the input DSA address is good. */ if (dsafmt8 == CEECAASTACK_UP) { long tptr = CeedsaTemplate.getCeedsanab(inputStream, callers_dsaptr); if (tptr == dsaptr) { log.finer("upstack DSA is good"); return 0; } } dsaptr = callers_dsaptr; /* We use the Tortoise and the Hare algorithm to detect loops. If the slow * iterator is lapped it means there is a loop. */ if (slow) { dsaf = new Ceexdsaf(space, slowdsaptr, slowdsafmt8, is64bit); slowdsaptr = dsaf.DSA_Prev; slowdsafmt8 = dsaf.DSA_Format; } if (dsaptr == slowdsaptr) { log.finer("loop detected in DSA chain"); return ERROR; } } } catch (IOException e) { /* Any bad read means the DSA was invalid */ log.logp(Level.FINER,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Bad read", e); return ERROR; } catch (Exception e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Unexepected exception", e); throw new Error("Unexpected Exception:: " + e); } } } |
blob | long method | t | t | f | long method | blob | 0 | 12698 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/corereaders/tdump/zebedee/le/Caa.java/#L348-L800 | 1 | 1996 | 12698 | critical |
| 2142 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13268 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 2 | 2142 | 13268 | major |
| 2275 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13773 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 2 | 2275 | 13773 | minor |
| 218 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HDFSTextLineReader { private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; private int bufferSize = DEFAULT_BUFFER_SIZE; private FSDataInputStream reader; private byte[] buffer; // the number of bytes of real data in the buffer private int bufferLength = 0; // the current position in the buffer private int bufferPosn = 0; private long currentFilePos = 0L; private static final byte CR = '\r'; private static final byte LF = '\n'; public static final String KEY_BUFFER_SIZE = "io.file.buffer.size"; /** * Create a line reader that reads from the given stream using the * default buffer-size (32k). * * @param in * The input stream * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in) throws IOException { this(in, DEFAULT_BUFFER_SIZE); } /** * Create a line reader that reads from the given stream using the * given buffer-size. * * @param in * The input stream * @param bufferSize * Size of the read buffer * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, int bufferSize) throws IOException { this.reader = in; this.bufferSize = bufferSize; this.buffer = new byte[this.bufferSize]; currentFilePos = in.getPos(); } public HDFSTextLineReader() throws IOException { this.bufferSize = DEFAULT_BUFFER_SIZE; this.buffer = new byte[this.bufferSize]; } /** * Create a line reader that reads from the given stream using the io.file.buffer.size specified in the given Configuration. * * @param in * input stream * @param conf * configuration * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, Configuration conf) throws IOException { this(in, conf.getInt(KEY_BUFFER_SIZE, DEFAULT_BUFFER_SIZE)); } /** * Read one line from the InputStream into the given Text. A line * can be terminated by one of the following: '\n' (LF) , '\r' (CR), * or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated * line. * * @param str * the object to store the given line (without newline) * @param maxLineLength * the maximum number of bytes to store into str; * the rest of the line is silently discarded. * @param maxBytesToConsume * the maximum number of bytes to consume * in this call. This is only a hint, because if the line cross * this threshold, we allow it to happen. It can overshoot * potentially by as much as one buffer length. * @return the number of bytes read including the (longest) newline * found. * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { /* We're reading data from in, but the head of the stream may be * already buffered in buffer, so we have several cases: * 1. No newline characters are in the buffer, so we need to copy * everything and read another buffer from the stream. * 2. An unambiguously terminated line is in buffer, so we just * copy to str. * 3. Ambiguously terminated line is in buffer, i.e. buffer ends * in CR. In this case we copy everything up to CR to str, but * we also need to see what follows CR: if it's LF, then we * need consume LF as well, so next call to readLine will read * from after that. * We use a flag prevCharCR to signal if previous character was CR * and, if it happens to be at the end of the buffer, delay * consuming it until we have a chance to look at the char that * follows. */ str.clear(); int txtLength = 0; //tracks str.getLength(), as an optimization int newlineLength = 0; //length of terminating newline boolean prevCharCR = false; //true of prev char was CR long bytesConsumed = 0; do { int startPosn = bufferPosn; //starting from where we left off the last time if (bufferPosn >= bufferLength) { startPosn = bufferPosn = 0; if (prevCharCR) ++bytesConsumed; //account for CR from previous read bufferLength = reader.read(buffer); if (bufferLength <= 0) break; // EOF } for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline if (buffer[bufferPosn] == LF) { newlineLength = (prevCharCR) ? 2 : 1; ++bufferPosn; // at next invocation proceed from following byte break; } if (prevCharCR) { //CR + notLF, we are at notLF newlineLength = 1; break; } prevCharCR = (buffer[bufferPosn] == CR); } int readLength = bufferPosn - startPosn; if (prevCharCR && newlineLength == 0) --readLength; //CR at the end of the buffer bytesConsumed += readLength; int appendLength = readLength - newlineLength; if (appendLength > maxLineLength - txtLength) { appendLength = maxLineLength - txtLength; } if (appendLength > 0) { str.append(buffer, startPosn, appendLength); txtLength += appendLength; } } while (newlineLength == 0 && bytesConsumed < maxBytesToConsume); if (bytesConsumed > Integer.MAX_VALUE) throw new IOException("Too many bytes before newline: " + bytesConsumed); currentFilePos = reader.getPos() - bufferLength + bufferPosn; return (int) bytesConsumed; } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @param maxLineLength * the maximum number of bytes to store into str. * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength) throws IOException { return readLine(str, maxLineLength, Integer.MAX_VALUE); } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str) throws IOException { return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE); } public void seek(long desired) throws IOException { if (reader.getPos() <= desired || currentFilePos > desired) { // desired position is ahead of stream or before the current position, seek to position reader.seek(desired); bufferLength = 0; bufferPosn = 0; currentFilePos = desired; } else if (currentFilePos < desired) { // desired position is in the buffer int difference = (int) (desired - currentFilePos); bufferPosn += difference; currentFilePos = desired; } } public FSDataInputStream getReader() { return reader; } public void resetReader(FSDataInputStream reader) throws IOException { this.reader = reader; bufferLength = 0; bufferPosn = 0; currentFilePos = reader.getPos(); } public void close() throws IOException { reader.close(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 2369 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/HDFSTextLineReader.java/#L27-L234 | 1 | 218 | 2369 | major |
| 2357 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14232 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 2357 | 14232 | major |
| 4965 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13592 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 2 | 4965 | 13592 | minor |
| 315 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3235 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 2 | 315 | 3235 | minor |
| 5309 | , I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14864 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 5309 | 14864 | minor | ||
| 2435 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14466 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 2435 | 14466 | minor |
| 675 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Incomplete code/undocumented code (TODO comments) 5. Inconsistent formatting (extra spaces and uneven indentation) 6. Unnecessary constructor overloading 7. Unnecessary getter and setter methods 8. Not using dependency injection consistently (mixing @Inject with constructor injection) 9. Non-descriptive variable names 10. Unused methods 11. Inconsistent naming of methods (e.g. getUuid() vs listVolumeIds()) 12. Large class (contains many methods and responsibilities) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
blob | Long method2 Feature envy3 Duplicate code4 Incomplete code/undocumented code (TODO comments)5 Inconsistent formatting (extra spaces and uneven indentation)6 Unnecessary constructor overloading7 Unnecessary getter and setter methods 8 Not using dependency injection consistently (mixing @Inject with constructor injection) 9 Non-descriptive variable names | t | f | f | . Long method2. Feature envy3. Duplicate code4. Incomplete code/undocumented code (TODO comments)5. Inconsistent formatting (extra spaces and uneven indentation)6. Unnecessary constructor overloading7. Unnecessary getter and setter methods 8. Not using dependency injection consistently (mixing @Inject with constructor injection) 9. Non-descriptive variable names | blob | 0 | 6572 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 2 | 675 | 6572 | minor |
| 1111 | {"message":"YES I found bad smells","bad smells are":["1. Long method","2. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | 1. long method, 2. blob | t | t | f | 1. long method, 2. blob | feature envy | 0 | 9888 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 1 | 1111 | 9888 | minor |
| 720 | YES I found bad smells. The bad smells are: 1. Feature envy: the class "ShadowNfcAdapter" is implementing the interface "NfcAdapter" instead of extending it, which means it is accessing the functionality of another class. 2. Long method: the method "getNfcAdapter(Context context)" is long and contains multiple statements, making it difficult to read and understand. 3. Long parameter list: the method "enableForegroundDispatch(Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists)" has a long list of parameters, which can be hard to work with and may indicate a potential design issue. 4. Shotgun surgery: the method "setNdefPushMessage(NdefMessage message, Activity activity, Activity... activities)" is modifying multiple fields of the class, which can make it difficult to track the changes and may indicate a need for better encapsulation. 5. Message chains: the class has multiple getter methods for various fields, which can lead to long chains of method calls in the client code. 6. Primitive obsession: the variables "enabled" and "hardwareExists" are set as booleans, and may indicate a need for refactoring to use more appropriate data types. 7. Feature envy: the getter methods are all directly accessing fields of the class, indicating a potential violation of encapsulation. 8. Lazy class: the class has many getter methods, but does not have any significant logic or functionality of its own. 9. Long class: the class has multiple fields and methods, which may indicate a need for refactoring to improve its cohesion. 10. Data class: the class only contains fields and getter/setter methods, and does not have any significant logic or functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
blob | Feature envy: the class "ShadowNfcAdapter" is implementing the interface "NfcAdapter" instead of extending it, which means it is accessing the functionality of another class2 Long method: the method "getNfcAdapter(Context context)" is long and contains multiple statements, making it difficult to read and understand3 Long parameter list: the method "enableForegroundDispatch(Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists)" has a long list of parameters, which can be hard to work with and may indicate a potential design issue4 Shotgun surgery: the method "setNdefPushMessage(NdefMessage message, Activity activity, Activity activities)" is modifying multiple fields of the class, which can make it difficult to track the changes and may indicate a need for better encapsulation5 Message chains: the class has multiple getter methods for various fields, which can lead to long chains of method calls in the client code6 Primitive obsession: the variables "enabled" and "hardwareExists" are set as booleans, and may indicate a need for refactoring to use more appropriate data types7 Feature envy: the getter methods are all directly accessing fields of the class, indicating a potential violation of encapsulation8 Lazy class: the class has many getter methods, but does not have any significant logic or functionality of its own9 Long class: the class has multiple fields and methods, which may indicate a need for refactoring to improve its cohesion | t | f | f | . Feature envy: the class "ShadowNfcAdapter" is implementing the interface "NfcAdapter" instead of extending it, which means it is accessing the functionality of another class.2. Long method: the method "getNfcAdapter(Context context)" is long and contains multiple statements, making it difficult to read and understand.3. Long parameter list: the method "enableForegroundDispatch(Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists)" has a long list of parameters, which can be hard to work with and may indicate a potential design issue.4. Shotgun surgery: the method "setNdefPushMessage(NdefMessage message, Activity activity, Activity... activities)" is modifying multiple fields of the class, which can make it difficult to track the changes and may indicate a need for better encapsulation.5. Message chains: the class has multiple getter methods for various fields, which can lead to long chains of method calls in the client code.6. Primitive obsession: the variables "enabled" and "hardwareExists" are set as booleans, and may indicate a need for refactoring to use more appropriate data types.7. Feature envy: the getter methods are all directly accessing fields of the class, indicating a potential violation of encapsulation.8. Lazy class: the class has many getter methods, but does not have any significant logic or functionality of its own.9. Long class: the class has multiple fields and methods, which may indicate a need for refactoring to improve its cohesion. | blob | 0 | 6830 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 2 | 720 | 6830 | minor |
| 103 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1357 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 2 | 103 | 1357 | minor |
| 237 | { "response": "YES, I found bad smells", "bad smells are:": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractBraveClientProvider extends AbstractTracingProvider { protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBraveClientProvider.class); protected static final String TRACE_SPAN = "org.apache.cxf.tracing.client.brave.span"; private final HttpTracing brave; public AbstractBraveClientProvider(final HttpTracing brave) { this.brave = brave; } protected TraceScopeHolder startTraceSpan(final Map> requestHeaders, URI uri, String method) { final Request request = HttpAdapterFactory.request(requestHeaders, uri, method); final HttpClientAdapter adapter = HttpClientAdapterFactory.create(request); final HttpClientHandler handler = HttpClientHandler.create(brave, adapter); final Span span = handler.handleSend( brave .tracing() .propagation() .injector(inject(requestHeaders)), request); // In case of asynchronous client invocation, the span should be detached as JAX-RS // client request / response filters are going to be executed in different threads. SpanInScope scope = null; if (!isAsyncInvocation() && span != null) { scope = brave.tracing().tracer().withSpanInScope(span); } return new TraceScopeHolder(new TraceScope(span, scope), scope == null /* detached */); } private Setter inject(final Map> requestHeaders) { return (carrier, key, value) -> { if (!requestHeaders.containsKey(key)) { requestHeaders.put(key, Collections.singletonList(value)); } }; } private boolean isAsyncInvocation() { return !PhaseInterceptorChain.getCurrentMessage().getExchange().isSynchronous(); } protected void stopTraceSpan(final TraceScopeHolder holder, final int responseStatus) { if (holder == null) { return; } final TraceScope scope = holder.getScope(); if (scope != null) { try { // If the client invocation was asynchronous , the trace span has been created // in another thread and should be re-attached to the current one. if (holder.isDetached()) { brave.tracing().tracer().joinSpan(scope.getSpan().context()); } final Response response = HttpAdapterFactory.response(responseStatus); final HttpClientAdapter adapter = HttpClientAdapterFactory.create(response); final HttpClientHandler handler = HttpClientHandler.create(brave, adapter); handler.handleReceive(response, null, scope.getSpan()); } finally { scope.close(); } } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2571 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/integration/tracing/tracing-brave/src/main/java/org/apache/cxf/tracing/brave/AbstractBraveClientProvider.java/#L41-L111 | 2 | 237 | 2571 | minor |
| 1056 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class HttpsTokenInInterceptor extends AbstractPhaseInterceptor { HttpsTokenInInterceptor() { super(Phase.PRE_STREAM); addBefore(WSS4JStaxInInterceptor.class.getName()); } public void handleMessage(Message message) throws Fault { AssertionInfoMap aim = message.get(AssertionInfoMap.class); // extract Assertion information if (aim != null) { Collection ais = PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.HTTPS_TOKEN); boolean requestor = isRequestor(message); if (ais.isEmpty()) { if (!requestor) { try { assertNonHttpsTransportToken(message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } } return; } if (!requestor) { try { assertHttps(aim, ais, message); } catch (XMLSecurityException e) { LOG.fine(e.getMessage()); } // Store the TLS principal on the message context SecurityContext sc = message.get(SecurityContext.class); if (sc == null || sc.getUserPrincipal() == null) { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null && tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0 && (tlsInfo.getPeerCertificates()[0] instanceof X509Certificate) ) { X509Certificate cert = (X509Certificate)tlsInfo.getPeerCertificates()[0]; message.put( SecurityContext.class, createSecurityContext(cert.getSubjectX500Principal()) ); } } } else { //client side should be checked on the way out for (AssertionInfo ai : ais) { ai.setAsserted(true); } PolicyUtils.assertPolicy(aim, SPConstants.HTTP_DIGEST_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.HTTP_BASIC_AUTHENTICATION); PolicyUtils.assertPolicy(aim, SPConstants.REQUIRE_CLIENT_CERTIFICATE); } } } private void assertHttps( AssertionInfoMap aim, Collection ais, Message message ) throws XMLSecurityException { List securityEvents = getSecurityEventList(message); AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); for (AssertionInfo ai : ais) { boolean asserted = true; HttpsToken token = (HttpsToken)ai.getAssertion(); HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); Map> headers = getProtocolHeaders(message); if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpBasicAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Basic")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpBasicAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(true, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_BASIC_AUTHENTICATION)); } } if (token.getAuthenticationType() == HttpsToken.AuthenticationType.HttpDigestAuthentication) { List auth = headers.get("Authorization"); if (auth == null || auth.isEmpty() || !auth.get(0).startsWith("Digest")) { asserted = false; } else { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpDigestAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(false, policy.getUserName()); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.HTTP_DIGEST_AUTHENTICATION)); } } TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { if (token.getAuthenticationType() == HttpsToken.AuthenticationType.RequireClientCertificate) { if (tlsInfo.getPeerCertificates() == null || tlsInfo.getPeerCertificates().length == 0) { asserted = false; } else { PolicyUtils.assertPolicy(aim, new QName(token.getName().getNamespaceURI(), SPConstants.REQUIRE_CLIENT_CERTIFICATE)); } } if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } } else { asserted = false; } ai.setAsserted(asserted); if (asserted) { securityEvents.add(httpsTokenSecurityEvent); } } } // We might have an IssuedToken TransportToken private void assertNonHttpsTransportToken(Message message) throws XMLSecurityException { TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class); if (tlsInfo != null) { HttpsTokenSecurityEvent httpsTokenSecurityEvent = new HttpsTokenSecurityEvent(); if (tlsInfo.getPeerCertificates() != null && tlsInfo.getPeerCertificates().length > 0) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsClientCertificateAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl((X509Certificate)tlsInfo.getPeerCertificates()[0]); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } else if (httpsTokenSecurityEvent.getAuthenticationType() == null) { httpsTokenSecurityEvent.setAuthenticationType( HttpsTokenSecurityEvent.AuthenticationType.HttpsNoAuthentication ); HttpsSecurityTokenImpl httpsSecurityToken = new HttpsSecurityTokenImpl(); httpsSecurityToken.addTokenUsage(WSSecurityTokenConstants.TOKENUSAGE_MAIN_SIGNATURE); httpsTokenSecurityEvent.setSecurityToken(httpsSecurityToken); } List securityEvents = getSecurityEventList(message); securityEvents.add(httpsTokenSecurityEvent); } } private List getSecurityEventList(Message message) { @SuppressWarnings("unchecked") List securityEvents = (List) message.getExchange().get(SecurityEvent.class.getName() + ".out"); if (securityEvents == null) { securityEvents = new ArrayList<>(); message.getExchange().put(SecurityEvent.class.getName() + ".out", securityEvents); } return securityEvents; } private SecurityContext createSecurityContext(final Principal p) { return new SecurityContext() { public Principal getUserPrincipal() { return p; } public boolean isUserInRole(String role) { return false; } }; } } |
blob | long method | t | t | f | long method | blob | 0 | 9514 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/HttpsTokenInterceptorProvider.java/#L191-L390 | 1 | 1056 | 9514 | major |
| 2488 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14613 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 2 | 2488 | 14613 | minor |
| 1507 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long method" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 11152 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 2 | 1507 | 11152 | critical |
| 1760 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 11890 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 2 | 1760 | 11890 | minor |
| 1084 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void createServerIdEditGroup( Composite parent ) { // ServerID Group Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "ServerID input", 1 ); GridLayout serverIdGroupGridLayout = new GridLayout( 2, false ); serverIdGroup.setLayout( serverIdGroupGridLayout ); serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // ServerID Text BaseWidgetUtils.createLabel( serverIdGroup, "ID:", 1 ); idText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // URL Text BaseWidgetUtils.createLabel( serverIdGroup, "URL:", 1 ); urlText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); urlText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9692 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.java/#L239-L256 | 1 | 1084 | 9692 | minor |
| 3994 | YES I found bad smells. the bad smells are: 1. Long method. 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method.2. Feature envy. | data class | 0 | 10543 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 2 | 3994 | 10543 | major |
| 3676 | { "response": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public WeightedAshwoodEntitySorter() { this.weightedDbEntityComparator = new WeightedDbEntityComparator(); this.weightedObjEntityComparator = new WeightedObjEntityComparator(); this.entityWeights = Collections.emptyMap(); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8524 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/ashwood/WeightedAshwoodEntitySorter.java/#L42-L46 | 1 | 3676 | 8524 | major |
| 887 | { "message": "YES I found bad smells", "detected_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 8072 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 | 1 | 887 | 8072 | minor |
| 1804 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 12026 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 | 1 | 1804 | 12026 | major |
| 1886 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12297 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 1886 | 12297 | major |
| 2510 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 14684 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 2510 | 14684 | major |
| 1189 | { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 10250 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 1189 | 10250 | major |
| 1584 | {"message": "YES, I found bad smells", "the bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TraversalFieldAccessorFactory implements FieldAccessorFactory { @Override public boolean accept(final Neo4JPersistentProperty f) { final GraphTraversal graphEntityTraversal = f.getAnnotation(GraphTraversal.class); return graphEntityTraversal != null && graphEntityTraversal.traversalBuilder() != FieldTraversalDescriptionBuilder.class && f.getType().equals(Iterable.class); } @Override public FieldAccessor forField(final Neo4JPersistentProperty property) { return new TraversalFieldAccessor(property); } /** * @author Michael Hunger * @since 12.09.2010 */ public static class TraversalFieldAccessor implements FieldAccessor { protected final Neo4JPersistentProperty property; private final FieldTraversalDescriptionBuilder fieldTraversalDescriptionBuilder; private Class target; protected String[] params; public TraversalFieldAccessor(final Neo4JPersistentProperty property) { this.property = property; final GraphTraversal graphEntityTraversal = property.getAnnotation(GraphTraversal.class); this.target = resolveTarget(graphEntityTraversal,property); this.params = graphEntityTraversal.params(); this.fieldTraversalDescriptionBuilder = createTraversalDescription(graphEntityTraversal); } private Class resolveTarget(GraphTraversal graphTraversal, Neo4JPersistentProperty property) { if (!graphTraversal.elementClass().equals(NodeBacked.class)) return graphTraversal.elementClass(); final Class result = property.getTypeInformation().getActualType().getType(); Class[] allowedTypes={NodeBacked.class,RelationshipBacked.class,Node.class,Relationship.class, Path.class}; if (!checkTypes(result,allowedTypes)) throw new IllegalArgumentException("The target result type "+result+" of the traversal is no subclass of the allowed types: "+property+" "+allowedTypes); return result; } private boolean checkTypes(Class target, Class...allowedTypes) { for (Class type : allowedTypes) { if (type.isAssignableFrom(target)) return true; } return false; } @Override public boolean isWriteable(NodeBacked nodeBacked) { return false; } @Override public Object setValue(final NodeBacked nodeBacked, final Object newVal) { throw new InvalidDataAccessApiUsageException("Cannot set readonly traversal description field " + property); } @Override public Object getValue(final NodeBacked nodeBacked) { final TraversalDescription traversalDescription = fieldTraversalDescriptionBuilder.build(nodeBacked, property,params); return doReturn(nodeBacked.findAllByTraversal(target, traversalDescription)); } private FieldTraversalDescriptionBuilder createTraversalDescription(final GraphTraversal graphEntityTraversal) { try { final Class traversalDescriptionClass = graphEntityTraversal.traversalBuilder(); final Constructor constructor = traversalDescriptionClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating TraversalDescription from " + property,e); } } @Override public Object getDefaultImplementation() { return null; } } } |
blob | 1 Long Method, 2 Data Class | t | f | f | 1. Long Method, 2. Data Class | blob | 0 | 11366 | https://github.com/spring-projects/spring-data-graph/blob/0210210ce436eb83bf200f5d5f9a63a440c5b27a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/fieldaccess/TraversalFieldAccessorFactory.java/#L36-L119 | 1 | 1584 | 11366 | minor |
| 593 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GwtDeviceServiceImpl extends KapuaRemoteServiceServlet implements GwtDeviceService { private static final long serialVersionUID = -1391026997499175151L; private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private boolean isSameId; @Override public GwtDevice findDevice(String scopeIdString, String deviceIdString) throws GwtKapuaException { GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = deviceRegistryService.find(scopeId, deviceId); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public ListLoadResult findDeviceProfile(String scopeIdString, String deviceIdString) throws GwtKapuaException { List pairs = new ArrayList(); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceEventService deviceEventService = locator.getService(DeviceEventService.class); final DeviceConnectionService deviceConnectionService = locator.getService(DeviceConnectionService.class); GroupService groupService = locator.getService(GroupService.class); final UserService userService = locator.getService(UserService.class); try { final KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); final Device device = deviceRegistryService.find(scopeId, deviceId); if (device != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devStatus", device.getStatus().toString())); final DeviceConnection deviceConnection; if (device.getConnectionId() != null) { if (device.getConnection() != null) { deviceConnection = device.getConnection(); } else { deviceConnection = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public DeviceConnection call() throws Exception { return deviceConnectionService.find(device.getScopeId(), device.getConnectionId()); } }); } } else { deviceConnection = null; } if (deviceConnection != null) { User lastConnectedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getUserId()); } }); User reservedUser = null; if (deviceConnection.getReservedUserId() != null) { reservedUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public User call() throws Exception { return userService.find(scopeId, deviceConnection.getReservedUserId()); } }); } pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", deviceConnection.getStatus().toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", lastConnectedUser != null ? lastConnectedUser.getName() : null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", reservedUser != null ? reservedUser.getName() : null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", GwtConnectionUserCouplingMode.valueOf(deviceConnection.getUserCouplingMode().name()).getLabel())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", device.getConnectionInterface())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", deviceConnection.getClientIp())); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", device.getConnectionIp())); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", deviceConnection.getStatus().toString())); } else { pairs.add(new GwtGroupedNVPair("connInfo", "connConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); pairs.add(new GwtGroupedNVPair("connInfo", "connClientId", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connUserName", null)); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new UserDomain(), Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair("connInfo", "connReservedUserId", null)); } pairs.add(new GwtGroupedNVPair("connInfo", "connUserCouplingMode", null)); pairs.add(new GwtGroupedNVPair("connInfo", "connClientIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIface", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIp", null)); pairs.add(new GwtGroupedNVPair("netInfo", "netConnIfaceIp", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); } pairs.add(new GwtGroupedNVPair("devInfo", "devClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair("devInfo", "devDisplayName", device.getDisplayName())); if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(new GroupDomain(), Actions.read, device.getScopeId()))) { if (device.getGroupId() != null) { Group group = groupService.find(scopeId, device.getGroupId()); if (group != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", group.getName())); } } else { pairs.add(new GwtGroupedNVPair("devInfo", "devGroupName", null)); } } if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { if (device.getLastEventId() != null) { DeviceEvent lastEvent = deviceEventService.find(scopeId, device.getLastEventId()); if (lastEvent != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", lastEvent.getResource())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", lastEvent.getReceivedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } else { if (deviceConnection != null) { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", deviceConnection.getStatus().name())); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", deviceConnection.getModifiedOn())); } else { pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventType", null)); pairs.add(new GwtGroupedNVPair("devInfo", "devLastEventOn", null)); } } } pairs.add(new GwtGroupedNVPair("devInfo", "devApps", device.getApplicationIdentifiers())); pairs.add(new GwtGroupedNVPair("devInfo", "devAccEnc", device.getAcceptEncoding())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute1", device.getCustomAttribute1())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute2", device.getCustomAttribute2())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute3", device.getCustomAttribute3())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute4", device.getCustomAttribute4())); pairs.add(new GwtGroupedNVPair("devAttributesInfo", "devCustomAttribute5", device.getCustomAttribute5())); pairs.add(new GwtGroupedNVPair("devHw", "devModelId", device.getModelId())); pairs.add(new GwtGroupedNVPair("devHw", "devModelName", device.getModelName())); pairs.add(new GwtGroupedNVPair("devHw", "devSerialNumber", device.getSerialNumber())); pairs.add(new GwtGroupedNVPair("devSw", "devFirmwareVersion", device.getFirmwareVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devBiosVersion", device.getBiosVersion())); pairs.add(new GwtGroupedNVPair("devSw", "devOsVersion", device.getOsVersion())); pairs.add(new GwtGroupedNVPair("devJava", "devJvmVersion", device.getJvmVersion())); // GPS infos retrieval if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(DeviceDomains.DEVICE_EVENT_DOMAIN, Actions.read, device.getScopeId()))) { DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); DeviceEventQuery eventQuery = deviceEventFactory .newQuery(device.getScopeId()); eventQuery.setLimit(1); eventQuery.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, device.getId())); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RESOURCE, "BIRTH")); eventQuery.setPredicate(andPredicate); KapuaListResult events = deviceEventService.query(eventQuery); DeviceEvent lastEvent = events.getFirstItem(); if (lastEvent != null) { KapuaPosition eventPosition = lastEvent.getPosition(); if (eventPosition != null) { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", String.valueOf(eventPosition.getLatitude()))); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", String.valueOf(eventPosition.getLongitude()))); } } else { pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLat", null)); pairs.add(new GwtGroupedNVPair("gpsInfo", "gpsLong", null)); } } pairs.add(new GwtGroupedNVPair("modemInfo", "modemImei", device.getImei())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemImsi", device.getImsi())); pairs.add(new GwtGroupedNVPair("modemInfo", "modemIccid", device.getIccid())); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return new BaseListLoadResult(pairs); } @Override public PagingLoadResult query(PagingLoadConfig loadConfig, GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); List gwtDevices = new ArrayList(); BasePagingLoadResult gwtResults; int totalResult = 0; try { DeviceQuery deviceQuery = GwtKapuaDeviceModelConverter.convertDeviceQuery(loadConfig, gwtDeviceQuery); deviceQuery.addFetchAttributes(DeviceAttributes.CONNECTION); deviceQuery.addFetchAttributes(DeviceAttributes.LAST_EVENT); KapuaListResult devices = deviceRegistryService.query(deviceQuery); totalResult = (int) deviceRegistryService.count(deviceQuery); for (Device d : devices.getItems()) { GwtDevice gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(d); // Connection info gwtDevice.setConnectionIp(d.getConnectionIp()); gwtDevice.setConnectionInterface(d.getConnectionInterface()); DeviceConnection deviceConnection = d.getConnection(); if (deviceConnection != null) { gwtDevice.setClientIp(deviceConnection.getClientIp()); gwtDevice.setGwtDeviceConnectionStatus(deviceConnection.getStatus().name()); gwtDevice.setLastEventOn(deviceConnection.getModifiedOn()); gwtDevice.setLastEventType(deviceConnection.getStatus().name()); } else { gwtDevice.setGwtDeviceConnectionStatus(GwtDeviceConnectionStatus.UNKNOWN.name()); } if (d.getLastEvent() != null) { DeviceEvent lastEvent = d.getLastEvent(); gwtDevice.setLastEventType(lastEvent.getResource()); gwtDevice.setLastEventOn(lastEvent.getReceivedOn()); } gwtDevices.add(gwtDevice); } } catch (Throwable t) { KapuaExceptionHandler.handle(t); } gwtResults = new BasePagingLoadResult(gwtDevices); gwtResults.setOffset(loadConfig != null ? loadConfig.getOffset() : 0); gwtResults.setTotalLength(totalResult); return gwtResults; } @Override public List query(GwtDeviceQuery gwtDeviceQuery) throws GwtKapuaException { return query(null, gwtDeviceQuery).getData(); } @Override public GwtDevice createDevice(GwtXSRFToken xsrfToken, GwtDeviceCreator gwtDeviceCreator) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtDeviceCreator.getScopeId()); DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId, gwtDeviceCreator.getClientId()); deviceCreator.setDisplayName(gwtDeviceCreator.getDisplayName()); deviceCreator.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceCreator.getGroupId())); deviceCreator.setStatus((DeviceStatus.valueOf(gwtDeviceCreator.getDeviceStatus()))); // FIXME One day it will be specified from the form. In the meantime, defaults to LOOSE // deviceCreator.setCredentialsMode(DeviceCredentialsMode.LOOSE); deviceCreator.setCustomAttribute1(gwtDeviceCreator.getCustomAttribute1()); deviceCreator.setCustomAttribute2(gwtDeviceCreator.getCustomAttribute2()); deviceCreator.setCustomAttribute3(gwtDeviceCreator.getCustomAttribute3()); deviceCreator.setCustomAttribute4(gwtDeviceCreator.getCustomAttribute4()); deviceCreator.setCustomAttribute5(gwtDeviceCreator.getCustomAttribute5()); Device device = deviceRegistryService.create(deviceCreator); gwtDevice = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDevice; } @Override public GwtDevice updateAttributes(GwtXSRFToken xsrfToken, GwtDevice gwtDevice) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); Device device = null; GwtDevice gwtDeviceUpdated = null; try { // // Find original device KapuaId scopeId = KapuaEid.parseCompactId(gwtDevice.getScopeId()); KapuaId deviceId = KapuaEid.parseCompactId(gwtDevice.getId()); device = deviceRegistryService.find(scopeId, deviceId); // // Updated values // Gerenal info device.setDisplayName(gwtDevice.getUnescapedDisplayName()); device.setStatus(DeviceStatus.valueOf(gwtDevice.getGwtDeviceStatus())); device.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDevice.getGroupId())); // Security Stuff // device.setCredentialsMode(DeviceCredentialsMode.valueOf(gwtDevice.getCredentialsTight())); // KapuaId deviceUserId = KapuaEid.parseCompactId(gwtDevice.getDeviceUserId()); // device.setPreferredUserId(deviceUserId); // Custom attributes device.setCustomAttribute1(gwtDevice.getUnescapedCustomAttribute1()); device.setCustomAttribute2(gwtDevice.getUnescapedCustomAttribute2()); device.setCustomAttribute3(gwtDevice.getUnescapedCustomAttribute3()); device.setCustomAttribute4(gwtDevice.getUnescapedCustomAttribute4()); device.setCustomAttribute5(gwtDevice.getUnescapedCustomAttribute5()); device.setOptlock(gwtDevice.getOptlock()); // Do the update device = deviceRegistryService.update(device); // Convert to gwt object gwtDeviceUpdated = KapuaGwtDeviceModelConverter.convertDevice(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtDeviceUpdated; } @Override public void deleteDevice(GwtXSRFToken xsrfToken, String scopeIdString, String clientId) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device d = drs.findByClientId(scopeId, clientId); drs.delete(d.getScopeId(), d.getId()); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void addDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); TagService tagService = locator.getService(TagService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); if (tagIds.contains(tagId)) { Tag tag = tagService.find(scopeId, tagId); isSameId = true; if (tag != null) { throw new KapuaDuplicateNameException(tag.getName()); } } tagIds.add(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public void deleteDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String tagIdString) throws GwtKapuaException { // // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); KapuaId tagId = KapuaEid.parseCompactId(tagIdString); KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService drs = locator.getService(DeviceRegistryService.class); Device device = drs.find(scopeId, deviceId); Set tagIds = device.getTagIds(); tagIds.remove(tagId); device.setTagIds(tagIds); drs.update(device); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } } @Override public PagingLoadResult findDeviceEvents(PagingLoadConfig loadConfig, GwtDevice gwtDevice, Date startDate, Date endDate) throws GwtKapuaException { ArrayList gwtDeviceEvents = new ArrayList(); BasePagingLoadResult gwtResults = null; KapuaLocator locator = KapuaLocator.getInstance(); DeviceEventService des = locator.getService(DeviceEventService.class); DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); try { // prepare the query BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig; DeviceEventQuery query = deviceEventFactory.newQuery(KapuaEid.parseCompactId(gwtDevice.getScopeId())); AndPredicate andPredicate = new AndPredicateImpl(); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.DEVICE_ID, KapuaEid.parseCompactId(gwtDevice.getId()))); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, startDate, Operator.GREATER_THAN)); andPredicate.and(new AttributePredicateImpl(DeviceEventAttributes.RECEIVED_ON, endDate, Operator.LESS_THAN)); query.setPredicate(andPredicate); query.setSortCriteria(new FieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); query.setOffset(bplc.getOffset()); query.setLimit(bplc.getLimit()); // query execute KapuaListResult deviceEvents = des.query(query); // prepare results for (DeviceEvent deviceEvent : deviceEvents.getItems()) { gwtDeviceEvents.add(KapuaGwtDeviceModelConverter.convertDeviceEvent(deviceEvent)); } gwtResults = new BasePagingLoadResult(gwtDeviceEvents); gwtResults.setOffset(loadConfig.getOffset()); gwtResults.setTotalLength((int) des.count(query)); } catch (Throwable t) { KapuaExceptionHandler.handle(t); } return gwtResults; } @Override public String getTileEndpoint() throws GwtKapuaException { return ConsoleSetting.getInstance().getString(ConsoleSettingKeys.DEVICE_MAP_TILE_URI); } @Override public boolean isMapEnabled() { return ConsoleSetting.getInstance().getBoolean(ConsoleSettingKeys.DEVICE_MAP_ENABLED); } } |
blob | long method | t | t | f | long method | blob | 0 | 5915 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java/#L88-L581 | 1 | 593 | 5915 | major |
| 1550 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11264 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 1550 | 11264 | major | ||
| 2211 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Primitive Obsession 5. Large Class/Class Too Many Responsibilities | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Parser { public static GetOrderReferenceDetailsResponseData getOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final GetOrderReferenceDetailsResponse response = marshalXML(GetOrderReferenceDetailsResponse.class, rawResponse); return new GetOrderReferenceDetailsResponseData(response, rawResponse); } public static SetOrderReferenceDetailsResponseData setOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final SetOrderReferenceDetailsResponse response = marshalXML(SetOrderReferenceDetailsResponse.class, rawResponse); return new SetOrderReferenceDetailsResponseData(response, rawResponse); } public static AuthorizeResponseData getAuthorizeData(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeResponse response = marshalXML(AuthorizeResponse.class, rawResponse); return new AuthorizeResponseData(response, rawResponse); } public static GetAuthorizationDetailsResponseData getAuthorizationDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetAuthorizationDetailsResponse response = marshalXML(GetAuthorizationDetailsResponse.class, rawResponse); return new GetAuthorizationDetailsResponseData(response, rawResponse); } public static CaptureResponseData getCapture(ResponseData rawResponse) throws AmazonServiceException { final CaptureResponse response = marshalXML(CaptureResponse.class, rawResponse); return new CaptureResponseData(response, rawResponse); } public static GetCaptureDetailsResponseData getCaptureDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetCaptureDetailsResponse response = marshalXML(GetCaptureDetailsResponse.class, rawResponse); return new GetCaptureDetailsResponseData(response, rawResponse); } public static ConfirmOrderReferenceResponseData confirmOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ConfirmOrderReferenceResponse response = marshalXML(ConfirmOrderReferenceResponse.class, rawResponse); return new ConfirmOrderReferenceResponseData(response, rawResponse); } public static CloseAuthorizationResponseData closeAuthorizationResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseAuthorizationResponse response = marshalXML(CloseAuthorizationResponse.class, rawResponse); return new CloseAuthorizationResponseData(response, rawResponse); } public static CancelOrderReferenceResponseData getCancelOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CancelOrderReferenceResponse response = marshalXML(CancelOrderReferenceResponse.class, rawResponse); return new CancelOrderReferenceResponseData(response, rawResponse); } public static CloseOrderReferenceResponseData getCloseOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CloseOrderReferenceResponse response = marshalXML(CloseOrderReferenceResponse.class, rawResponse); return new CloseOrderReferenceResponseData(response, rawResponse); } public static RefundResponseData getRefundData(ResponseData rawResponse) throws AmazonServiceException { final RefundResponse response = marshalXML(RefundResponse.class, rawResponse); return new RefundResponseData(response, rawResponse); } public static GetRefundDetailsResponseData getRefundDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetRefundDetailsResponse response = marshalXML(GetRefundDetailsResponse.class, rawResponse); return new GetRefundDetailsResponseData(response, rawResponse); } public static GetBillingAgreementDetailsResponseData getBillingAgreementDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetBillingAgreementDetailsResponse response = marshalXML(GetBillingAgreementDetailsResponse.class, rawResponse); return new GetBillingAgreementDetailsResponseData(response, rawResponse); } public static SetBillingAgreementDetailsResponseData getSetBillingAgreementDetailsResponse(ResponseData rawResponse) throws AmazonServiceException { final SetBillingAgreementDetailsResponse response = marshalXML(SetBillingAgreementDetailsResponse.class, rawResponse); return new SetBillingAgreementDetailsResponseData(response, rawResponse); } public static ValidateBillingAgreementResponseData getValidateBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ValidateBillingAgreementResponse response = marshalXML(ValidateBillingAgreementResponse.class, rawResponse); return new ValidateBillingAgreementResponseData(response, rawResponse); } public static ConfirmBillingAgreementResponseData confirmBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ConfirmBillingAgreementResponse response = marshalXML(ConfirmBillingAgreementResponse.class, rawResponse); return new ConfirmBillingAgreementResponseData(response, rawResponse); } public static AuthorizeOnBillingAgreementResponseData getAuthorizeOnBillingAgreement(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeOnBillingAgreementResponse response = marshalXML(AuthorizeOnBillingAgreementResponse.class, rawResponse); return new AuthorizeOnBillingAgreementResponseData(response, rawResponse); } public static CloseBillingAgreementResponseData closeBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseBillingAgreementResponse response = marshalXML(CloseBillingAgreementResponse.class, rawResponse); return new CloseBillingAgreementResponseData(response, rawResponse); } public static GetProviderCreditDetailsResponseData getGetProviderCreditDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditDetailsResponse response = marshalXML(GetProviderCreditDetailsResponse.class, rawResponse); return new GetProviderCreditDetailsResponseData(response, rawResponse); } public static GetProviderCreditReversalDetailsResponseData getProviderCreditReversalDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditReversalDetailsResponse response = marshalXML(GetProviderCreditReversalDetailsResponse.class, rawResponse); return new GetProviderCreditReversalDetailsResponseData(response, rawResponse); } public static ReverseProviderCreditResponseData getReverseProviderCreditResponseData(ResponseData rawResponse) throws AmazonServiceException { final ReverseProviderCreditResponse response = marshalXML(ReverseProviderCreditResponse.class, rawResponse); return new ReverseProviderCreditResponseData(response, rawResponse); } public static GetServiceStatusResponseData getServiceStatus( ResponseData rawResponse) throws AmazonServiceException { final GetServiceStatusResponse response = marshalXML( GetServiceStatusResponse.class, rawResponse); return new GetServiceStatusResponseData(response, rawResponse); } public static CreateOrderReferenceForIdResponseData createOrderReferenceForId( ResponseData rawResponse) throws AmazonServiceException { final CreateOrderReferenceForIdResponse response = marshalXML( CreateOrderReferenceForIdResponse.class, rawResponse); return new CreateOrderReferenceForIdResponseData(response, rawResponse); } public static ListOrderReferenceResponseData listOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceResponse response = marshalXML(ListOrderReferenceResponse.class, rawResponse); return new ListOrderReferenceResponseData(response, rawResponse); } public static ListOrderReferenceByNextTokenResponseData listOrderReferenceByNextToken(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceByNextTokenResponse response = marshalXML(ListOrderReferenceByNextTokenResponse.class, rawResponse); return new ListOrderReferenceByNextTokenResponseData(response, rawResponse); } public static SetOrderAttributesResponseData setOrderAttributes(ResponseData rawResponse) throws AmazonServiceException { final SetOrderAttributesResponse response = marshalXML(SetOrderAttributesResponse.class, rawResponse); return new SetOrderAttributesResponseData(response, rawResponse); } public static GetMerchantAccountStatusResponseData getMerchantAccountStatus(ResponseData rawResponse) throws AmazonServiceException { final GetMerchantAccountStatusResponse response = marshalXML(GetMerchantAccountStatusResponse.class, rawResponse); return new GetMerchantAccountStatusResponseData(response, rawResponse); } public static T marshalXML(Class clazz, ResponseData rawResponse) throws AmazonServiceException { try { if (rawResponse.getStatusCode() == 200) { T responseObject = null; final JAXBContext context = JAXBContext.newInstance(clazz); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); responseObject = (T) unmarshaller.unmarshal(xmlStreamReader); return responseObject; } else { generateErrorException(rawResponse); } } catch (JAXBException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } return null; } public static void generateErrorException(ResponseData rawResponse) throws AmazonServiceException, JAXBException { final JAXBContext context = JAXBContext.newInstance(ErrorResponse.class); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); try { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); final ErrorResponse result = (ErrorResponse) unmarshaller.unmarshal(xmlStreamReader); throw new AmazonServiceException(result, rawResponse); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } } } |
blob | Long Method2 Feature Envy3 Duplicate Code4 Primitive Obsession5 Large Class/Class Too Many Responsibilities | t | f | f | . Long Method2. Feature Envy3. Duplicate Code4. Primitive Obsession5. Large Class/Class Too Many Responsibilities | blob | 0 | 13521 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/parser/Parser.java/#L57-L252 | 2 | 2211 | 13521 | major |
| 2526 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } } |
data class | long method | t | t | f | long method | data class | 0 | 14723 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 | 1 | 2526 | 14723 | minor |
| 1767 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class OgnlHelper { private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); private OgnlHelper() { } /** * Tests whether or not the given String is a Camel OGNL expression. * * An expression is considered an OGNL expression when it contains either one of the following chars: . or [ * * @param expression the String * @return true if a Camel OGNL expression, otherwise false. */ public static boolean isValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } // the brackets should come in a pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 && bracketEnd > 0) { return bracketBegin == bracketEnd; } return expression.contains("."); } public static boolean isInvalidValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) { return false; } // the brackets should come in pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 || bracketEnd > 0) { return bracketBegin != bracketEnd; } // check for double dots if (expression.contains("..")) { return true; } return false; } /** * Validates whether the method name is using valid java identifiers in the name * Will throw {@link IllegalArgumentException} if the method name is invalid. */ public static void validateMethodName(String method) { if (ObjectHelper.isEmpty(method)) { return; } for (int i = 0; i < method.length(); i++) { char ch = method.charAt(i); if (i == 0 && '.' == ch) { // its a dot before a method name continue; } if (ch == '(' || ch == '[' || ch == '.' || ch == '?') { // break when method name ends and sub method or arguments begin break; } if (i == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method); } } } /** * Tests whether or not the given Camel OGNL expression is using the null safe operator or not. * * @param ognlExpression the Camel OGNL expression * @return true if the null safe operator is used, otherwise false. */ public static boolean isNullSafeOperator(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return false; } return ognlExpression.startsWith("?"); } /** * Removes any leading operators from the Camel OGNL expression. * * Will remove any leading of the following chars: ? or . * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any leading operators. */ public static String removeLeadingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.startsWith("?")) { ognlExpression = ognlExpression.substring(1); } if (ognlExpression.startsWith(".")) { ognlExpression = ognlExpression.substring(1); } return ognlExpression; } /** * Removes any trailing operators from the Camel OGNL expression. * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any trailing operators. */ public static String removeTrailingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.contains("[")) { return StringHelper.before(ognlExpression, "["); } return ognlExpression; } public static String removeOperators(String ognlExpression) { return removeLeadingOperators(removeTrailingOperators(ognlExpression)); } public static KeyValueHolder isOgnlIndex(String ognlExpression) { Matcher matcher = INDEX_PATTERN.matcher(ognlExpression); if (matcher.matches()) { // to avoid empty strings as we want key/value to be null in such cases String key = matcher.group(1); if (ObjectHelper.isEmpty(key)) { key = null; } // to avoid empty strings as we want key/value to be null in such cases String value = matcher.group(2); if (ObjectHelper.isEmpty(value)) { value = null; } return new KeyValueHolder<>(key, value); } return null; } /** * Regular expression with repeating groups is a pain to get right * and then nobody understands the reg exp afterwards. * So we use a bit ugly/low-level Java code to split the OGNL into methods. * * @param ognl the ognl expression * @return a list of methods, will return an empty list, if ognl expression has no methods * @throws IllegalArgumentException if the last method has a missing ending parenthesis */ public static List splitOgnl(String ognl) { List methods = new ArrayList<>(); // return an empty list if ognl is empty if (ObjectHelper.isEmpty(ognl)) { return methods; } StringBuilder sb = new StringBuilder(); int j = 0; // j is used as counter per method boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo] boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo}) for (int i = 0; i < ognl.length(); i++) { char ch = ognl.charAt(i); // special for starting a new method if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?') || (ch != '.' && ch != '?' && ch != ']')) { sb.append(ch); // special if we are doing square bracket if (ch == '[' && !parenthesisBracket) { squareBracket = true; } else if (ch == '(') { parenthesisBracket = true; } else if (ch == ')') { parenthesisBracket = false; } j++; // advance } else { if (ch == '.' && !squareBracket && !parenthesisBracket) { // only treat dot as a method separator if not inside a square bracket block // as dots can be used in key names when accessing maps // a dit denotes end of this method and a new method is to be invoked String s = sb.toString(); // reset sb sb.setLength(0); // pass over ? to the new method if (s.endsWith("?")) { sb.append("?"); s = s.substring(0, s.length() - 1); } // add the method methods.add(s); // reset j to begin a new method j = 0; } else if (ch == ']' && !parenthesisBracket) { // append ending ] to method name sb.append(ch); String s = sb.toString(); // reset sb sb.setLength(0); // add the method methods.add(s); // reset j to begin a new method j = 0; // no more square bracket squareBracket = false; } // and don't lose the char if its not an ] end marker (as we already added that) if (ch != ']' || parenthesisBracket) { sb.append(ch); } // only advance if already begun on the new method if (j > 0) { j++; } } } // add remainder in buffer when reached end of data if (sb.length() > 0) { methods.add(sb.toString()); } String last = methods.isEmpty() ? null : methods.get(methods.size() - 1); if (parenthesisBracket && last != null) { // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis if (last.contains("(") && !last.endsWith(")")) { throw new IllegalArgumentException("Method should end with parenthesis, was " + last); } } return methods; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11912 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-util/src/main/java/org/apache/camel/util/OgnlHelper.java/#L27-L292 | 2 | 1767 | 11912 | major |
| 406 | {"response": "YES, I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void delete(UserInfo user) throws CoreException { JSONObject sites = getSites(user); if (!sites.has(getId())) { //nothing to do, site does not exist return; } sites.remove(getId()); user.setProperty(SiteConfigurationConstants.KEY_SITE_CONFIGURATIONS, sites.toString()); OrionConfiguration.getMetaStore().updateUser(user); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 4144 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/SiteInfo.java/#L150-L159 | 1 | 406 | 4144 | major |
| 4227 | { private int[][][] values; public ArrayImageSource( int width, int height, int[][][] values ) { super( width, height ); this.values = values; } public int getRGB( int x, y ) { return values[x][y][0] << 16 | values[x][y][1] << 8 | values[x][y][2]; } protected int height; protected int width; public ImageSource( int width, int height ) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | 6 | values[x][y][ | f | f | f | 6 | values[x][y][ | data class | 0 | 11130 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 2 | 4227 | 11130 | critical |
| 207 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2307 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 | 2 | 207 | 2307 | major |
| 93 | { "response": "YES I found bad smells", "bad smells are": "1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1252 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 2 | 93 | 1252 | major |
| 3811 | { "input_code": "public class Product {\n private String name;\n private double price;\n public Product(String name, double price) {\n this.name = name;\n this.price = price;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public double calculateTax() {\n return price * 0.1;\n }\n}", "code_smells_to_check": ["Blob", "Data Class", "Feature Envy", "Long Method"], "detected_code_smells": [] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | t | t | f | feature envy | 0 | 9700 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 1 | 3811 | 9700 | minor | ||
| 1917 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
blob | data class | t | t | f | data class | blob | 0 | 12409 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 1917 | 12409 | minor |
| 94 | {"response": "YES I found bad smells", "the bad smells are": [ "Long method", "Magic strings" ]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ServletConstants { String PAGE_HEADER = "\n" + "\n" + "\n" + " \n" + " Weblogic Monitoring Exporter\n" + "\n" + ""; // The locations of the servlets relative to the web app String MAIN_PAGE = ""; String METRICS_PAGE = "metrics"; String CONFIGURATION_PAGE = "configure"; /** The header used by a web client to send its authentication credentials. **/ String AUTHENTICATION_HEADER = "Authorization"; /** The header used by a web client to send cookies as part of a request. */ String COOKIE_HEADER = "Cookie"; // The field which defines the configuration update action String EFFECT_OPTION = "effect"; // The possible values for the effect String DEFAULT_ACTION = ServletConstants.REPLACE_ACTION; String REPLACE_ACTION = "replace"; String APPEND_ACTION = "append"; } |
data class | long method, magic strings | t | t | f | long method, magic strings | data class | 0 | 1261 | https://github.com/oracle/weblogic-monitoring-exporter/blob/05f1d3c4cc797577801df0ceceb9d92fc31718e8/src/main/java/io/prometheus/wls/rest/ServletConstants.java/#L13-L41 | 2 | 94 | 1261 | minor |
| 500 | YES I found bad smells the bad smells are: 1. Long method 2. Data clumps 3. Duplicated code 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method2 Data clumps3 Duplicated code4 Feature envy | t | f | f | . Long method2. Data clumps3. Duplicated code4. Feature envy | data class | 0 | 5070 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 500 | 5070 | major |
| 126 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 1575 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 1 | 126 | 1575 | minor |
| 510 | {"message": "YES I found bad smells", "bad smells are:": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | long method | t | t | f | long method | data class | 0 | 5190 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 1 | 510 | 5190 | major |
| 135 | {"response": "YES, I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1664 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 135 | 1664 | major |
| 842 | {"response": "YES I found bad smells", "bad smells are": ["Large class", "Long method", "Feature envy", "Duplicate code"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } } |
data class | large class, long method, feature envy, duplicate code | t | t | f | large class, long method, feature envy, duplicate code | data class | 0 | 7803 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 | 2 | 842 | 7803 | minor |
| 2424 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 14443 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 2424 | 14443 | critical |
| 146 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | long method | t | t | f | long method | data class | 0 | 1826 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 1 | 146 | 1826 | minor |
| 1924 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12432 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 2 | 1924 | 12432 | major |
| 3476 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Complicated code structure and high complexity 5. Inconsistent naming conventions 6. Inadequate or incomplete comments and documentation 7. Lack of clear separation of concerns and responsibilities 8. Inefficient use of data structures and algorithms 9. Unnecessary use of static methods 10. Overuse of inheritance and abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractClientProvider { public AbstractClientProvider() { } /** * Generates a fixed format of application tags given one or more of * application name, version and description. This allows subsequent query for * an application with a name only, version only or description only or any * combination of those as filters. * * @param appName name of the application * @param appVersion version of the application * @param appDescription brief description of the application * @return */ public static final Set createApplicationTags(String appName, String appVersion, String appDescription) { Set tags = new HashSet<>(); tags.add(ServiceUtils.createNameTag(appName)); if (appVersion != null) { tags.add(ServiceUtils.createVersionTag(appVersion)); } if (appDescription != null) { tags.add(ServiceUtils.createDescriptionTag(appDescription)); } return tags; } /** * Validate the artifact. * @param artifact */ public abstract void validateArtifact(Artifact artifact, String compName, FileSystem fileSystem) throws IOException; protected abstract void validateConfigFile(ConfigFile configFile, String compName, FileSystem fileSystem) throws IOException; /** * Validate the config files. * @param configFiles config file list * @param fs file system */ public void validateConfigFiles(List configFiles, String compName, FileSystem fs) throws IOException { Set destFileSet = new HashSet<>(); for (ConfigFile file : configFiles) { if (file.getType() == null) { throw new IllegalArgumentException("File type is empty"); } ConfigFile.TypeEnum fileType = file.getType(); if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) { if (StringUtils.isEmpty(file.getSrcFile()) && !file.getProperties().containsKey(CONTENT)) { throw new IllegalArgumentException(MessageFormat.format("For {0} " + "format, either src_file must be specified in ConfigFile," + " or the \"{1}\" key must be specified in " + "the 'properties' field of ConfigFile. ", ConfigFile.TypeEnum.TEMPLATE, CONTENT)); } } else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals( ConfigFile.TypeEnum.ARCHIVE)) { if (!file.getProperties().isEmpty()) { throw new IllegalArgumentException(String .format("For %s format, should not specify any 'properties.'", fileType)); } String srcFile = file.getSrcFile(); if (srcFile == null || srcFile.isEmpty()) { throw new IllegalArgumentException(String.format( "For %s format, should make sure that srcFile is specified", fileType)); } FileStatus fileStatus = fs.getFileStatus(new Path(srcFile)); if (fileStatus != null && fileStatus.isDirectory()) { throw new IllegalArgumentException("srcFile=" + srcFile + " is a directory, which is not supported."); } } if (!StringUtils.isEmpty(file.getSrcFile())) { Path p = new Path(file.getSrcFile()); if (!fs.exists(p)) { throw new IllegalArgumentException( "Specified src_file does not exist on " + fs.getScheme() + ": " + file.getSrcFile()); } } if (StringUtils.isEmpty(file.getDestFile())) { throw new IllegalArgumentException("dest_file is empty."); } if (destFileSet.contains(file.getDestFile())) { throw new IllegalArgumentException( "Duplicated ConfigFile exists: " + file.getDestFile()); } destFileSet.add(file.getDestFile()); java.nio.file.Path destPath = Paths.get(file.getDestFile()); if (!destPath.isAbsolute() && destPath.getNameCount() > 1) { throw new IllegalArgumentException("Non-absolute dest_file has more " + "than one path element"); } // provider-specific validation validateConfigFile(file, compName, fs); } } } |
blob | Long method2 Feature envy3 Duplicated code4 Complicated code structure and high complexity5 Inconsistent naming conventions6 Inadequate or incomplete comments and documentation7 Lack of clear separation of concerns and responsibilities8 Inefficient use of data structures and algorithms9 Unnecessary use of static methods | t | f | f | . Long method2. Feature envy3. Duplicated code4. Complicated code structure and high complexity5. Inconsistent naming conventions6. Inadequate or incomplete comments and documentation7. Lack of clear separation of concerns and responsibilities8. Inefficient use of data structures and algorithms9. Unnecessary use of static methods | blob | 0 | 7072 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/AbstractClientProvider.java/#L38-L150 | 2 | 3476 | 7072 | major |
| 5535 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 6189 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5535 | 6189 | major |
| 4100 | { "NO, I did not find any bad smell" :"" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_LOCATION = 1; private static final String NEARBY_BEACONS_FRAGMENT_TAG = "NearbyBeaconsFragmentTag"; private static final String SETTINGS_FRAGMENT_TAG = "SettingsFragmentTag"; private static final String BLOCKED_URLS_FRAGMENT_TAG = "BlockedUrlsFragmentTag"; private static final String ABOUT_FRAGMENT_TAG = "AboutFragmentTag"; private static final String DEMOS_FRAGMENT_TAG = "DemosFragmentTag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Utils.setSharedPreferencesDefaultValues(this); PermissionCheck.getInstance().setCheckingPermissions(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * Called when a menu item is tapped. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // If the about menu item was selected case R.id.action_about: showAboutFragment(); return true; // If the settings menu item was selected case R.id.action_settings: showSettingsFragment(); return true; case R.id.block_settings: showBlockedFragment(); return true; case R.id.action_demos: showDemosFragment(); return true; // If the action bar up button was pressed case android.R.id.home: getFragmentManager().popBackStack(); getActionBar().setDisplayHomeAsUpEnabled(false); } return super.onOptionsItemSelected(item); } /** * Ensures Bluetooth is available on the beacon and it is enabled. If not, * displays a dialog requesting user permission to enable Bluetooth. */ private void checkPermissions(BluetoothAdapter bluetoothAdapter) { // Acquire lock PermissionCheck.getInstance().setCheckingPermissions(true); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } ensureLocationPermissionIsEnabled(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == REQUEST_ENABLE_BT && resultCode == -1) { ensureLocationPermissionIsEnabled(); return; } Toast.makeText(this, getString(R.string.bt_on), Toast.LENGTH_LONG).show(); finish(); } private void ensureLocationPermissionIsEnabled() { if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ android.Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } PermissionCheck.getInstance().setCheckingPermissions(false); finishLoad(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionCheck.getInstance().setCheckingPermissions(false); } else { Toast.makeText(getApplicationContext(), getString(R.string.loc_permission), Toast.LENGTH_LONG).show(); finish(); } break; } default: } } @Override protected void onResume() { super.onResume(); // Lock to prevent onResume from running until all permissions are granted if (!PermissionCheck.getInstance().isCheckingPermissions()) { Log.d(TAG, "resumed MainActivity"); BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = btManager != null ? btManager.getAdapter() : null; if (btAdapter == null) { Toast.makeText(getApplicationContext(), R.string.error_bluetooth_support, Toast.LENGTH_LONG).show(); finish(); return; } if (Utils.checkIfUserHasOptedIn(this)) { Log.d(TAG, "checkingPermissions"); checkPermissions(btAdapter); } else { // Show the oob activity Intent intent = new Intent(this, OobActivity.class); startActivity(intent); } } } private void finishLoad() { Intent intent = new Intent(this, ScreenListenerService.class); startService(intent); NearbyBeaconsFragment nearbyBeaconsFragment = (NearbyBeaconsFragment) getFragmentManager().findFragmentByTag(NEARBY_BEACONS_FRAGMENT_TAG); if (nearbyBeaconsFragment != null) { nearbyBeaconsFragment.restartScan(); } else { showFragment(new NearbyBeaconsFragment(), NEARBY_BEACONS_FRAGMENT_TAG, false); } } /** * Show the fragment to configure the app. */ private void showSettingsFragment() { showFragment(new SettingsFragment(), SETTINGS_FRAGMENT_TAG, true); } /** * Show the fragment displaying information about this application. */ private void showAboutFragment() { showFragment(new AboutFragment(), ABOUT_FRAGMENT_TAG, true); } /** * Show the fragment displaying the blocked URLs. */ private void showBlockedFragment() { showFragment(new BlockedFragment(), BLOCKED_URLS_FRAGMENT_TAG, true); } /** * Show the fragment displaying the demos. */ private void showDemosFragment() { showFragment(new DemosFragment(), DEMOS_FRAGMENT_TAG, true); } @SuppressLint("CommitTransaction") private void showFragment(Fragment newFragment, String fragmentTag, boolean addToBackStack) { FragmentTransaction transaction = getFragmentManager().beginTransaction() .setCustomAnimations( R.animator.fade_in_and_slide_up_fragment, R.animator.fade_out_fragment, R.animator.fade_in_activity, R.animator.fade_out_fragment) .replace(R.id.main_activity_container, newFragment, fragmentTag); if (addToBackStack) { transaction.addToBackStack(null); } transaction.commit(); } } |
blob | f | f | f | blob | 0 | 10801 | https://github.com/google/physical-web/blob/12604319e99b6d6dff451fc5a58a13a271f1dc7a/android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/MainActivity.java/#L39-L228 | 1 | 4100 | 10801 | major | ||
| 529 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | data class | t | t | f | data class | blob | 0 | 5454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 1 | 529 | 5454 | minor |
| 744 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | data class | t | t | f | data class | blob | 0 | 7006 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 1 | 744 | 7006 | critical |
| 121 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Blob", "2. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void formatElement(IProgressMonitor monitor) { FormatProcessorXML formatProcessor = new FormatProcessorXML(); formatProcessor.setProgressMonitor(monitor); formatProcessor.getFormatPreferences().setClearAllBlankLines(true); formatProcessor.formatModel(model); CleanupProcessorXML bla = new CleanupProcessorXML(); bla.getCleanupPreferences().setCompressEmptyElementTags(true); bla.cleanupModel(model); } |
feature envy | 1. blob, 2. long method | t | t | f | 1. blob, 2. long method | feature envy | 0 | 1534 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.webflow.ui.graph/src/org/springframework/ide/eclipse/webflow/ui/graph/WebflowEditor.java/#L578-L587 | 1 | 121 | 1534 | minor |
| 514 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5287 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 2 | 514 | 5287 | major |
| 572 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 5756 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 572 | 5756 | minor |
| 1508 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11154 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 2 | 1508 | 11154 | major |
| 1512 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11160 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1512 | 11160 | minor |
| 1073 | {"response": "YES I found bad smells", "bad smells are:": "1. Long method", "2. Feature envy" : ["storeWorkflowJobDetails", "persistWorkflowJobInfo", "persistCoordinatorJobInfo", "persistBundleJobInfo", "storeCommonDetails", "persistJobLog", "persistJobProperties", "persistWorkflowDefinition", "storeLastWorkflows", "storeLastCoordinators", "storeLastBundles", "getSpecificJobs"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 9620 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 2 | 1073 | 9620 | minor |
| 96 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | long method | t | t | f | long method | blob | 0 | 1275 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 2 | 96 | 1275 | critical |
| 2543 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14787 | https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 | 2 | 2543 | 14787 | minor |
| 1327 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10704 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 2 | 1327 | 10704 | major |
| 1096 | YES, I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { /** * @see AddDomainOptions#primaryNameServer */ public static AddDomainOptions primaryNameServer(String primaryNameServer) { return AddDomainOptions.class.cast(new AddDomainOptions().primaryNameServer(primaryNameServer)); } /** * @see AddDomainOptions#responsiblePerson */ public static AddDomainOptions responsiblePerson(String responsiblePerson) { return AddDomainOptions.class.cast(new AddDomainOptions().responsiblePerson(responsiblePerson)); } /** * @see AddDomainOptions#ttl */ public static AddDomainOptions ttl(int ttl) { return AddDomainOptions.class.cast(new AddDomainOptions().ttl(ttl)); } /** * @see AddDomainOptions#refresh */ public static AddDomainOptions refresh(int refresh) { return AddDomainOptions.class.cast(new AddDomainOptions().refresh(refresh)); } /** * @see AddDomainOptions#retry */ public static AddDomainOptions retry(int retry) { return AddDomainOptions.class.cast(new AddDomainOptions().retry(retry)); } /** * @see AddDomainOptions#expire */ public static AddDomainOptions expire(int expire) { return AddDomainOptions.class.cast(new AddDomainOptions().expire(expire)); } /** * @see AddDomainOptions#minimum */ public static AddDomainOptions minimum(int minimum) { return AddDomainOptions.class.cast(new AddDomainOptions().minimum(minimum)); } /** * @see AddDomainOptions#minimalRecords */ public static AddDomainOptions minimalRecords() { return AddDomainOptions.class.cast(new AddDomainOptions().minimalRecords()); } } |
blob | Feature envy | t | f | f | . Feature envy | blob | 0 | 9783 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java/#L21-L77 | 2 | 1096 | 9783 | major |
| 1757 | YES I found bad smells The bad smells are: 1. Many queries and named queries combined in one class, resulting in a high complexity and decreased readability. 2. The use of abbreviations for variable names, making the code less readable and hard to understand. 3. The use of getters and setters for almost every property, which can lead to feature envy and bloated classes. 4. The use of defaultString() in getters, indicating a possible problem with handling null values. 5. The use of CascadeType.ALL and CascadeType.REMOVE in many places, which could lead to potential issues with cascading behavior. 6. The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly. 7. The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to. 8. The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | Many queries and named queries combined in one class, resulting in a high complexity and decreased readability2 The use of abbreviations for variable names, making the code less readable and hard to understand3 The use of getters and setters for almost every property, which can lead to feature envy and bloated classes4 The use of defaultString() in getters, indicating a possible problem with handling null values5 The use of CascadeTypeALL and CascadeTypeREMOVE in many places, which could lead to potential issues with cascading behavior6 The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly7 The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to8 The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle | t | f | f | . Many queries and named queries combined in one class, resulting in a high complexity and decreased readability.2. The use of abbreviations for variable names, making the code less readable and hard to understand.3. The use of getters and setters for almost every property, which can lead to feature envy and bloated classes.4. The use of defaultString() in getters, indicating a possible problem with handling null values.5. The use of CascadeType.ALL and CascadeType.REMOVE in many places, which could lead to potential issues with cascading behavior.6. The use of the @Basic annotation for some properties, which suggests that the mapping could have been done differently and more explicitly.7. The use of @JoinColumn with insertable and updatable flags set to true, suggesting that the entity might not be fully designed for the database it should be mapped to.8. The entity class is quite large and contains many properties and relationships, indicating a possible violation of the Single Responsibility Principle. | data class | 0 | 11877 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 2 | 1757 | 11877 | major |
| 446 | YES I found bad smells the bad smells are: 1.Long method 2.Low cohesion 3.Magic numbers 4.Inefficient variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class Attributes implements AttributeList { private int _element; private DOM _document; public Attributes(DOM document, int element) { _element = element; _document = document; } public int getLength() { return 0; } public String getName(int i) { return null; } public String getType(int i) { return null; } public String getType(String name) { return null; } public String getValue(int i) { return null; } public String getValue(String name) { return null; } } |
data class | Long method 2Low cohesion 3Magic numbers 4Inefficient variable naming | t | f | f | .Long method 2.Low cohesion 3.Magic numbers 4.Inefficient variable naming | data class | 0 | 4357 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/runtime/Attributes.java/#L31-L63 | 2 | 446 | 4357 | major |
| 2316 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | data class | t | t | f | data class | feature envy | 0 | 14118 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 2316 | 14118 | minor |
| 3587 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 7921 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 2 | 3587 | 7921 | minor | ||
| 2687 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 15282 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 2687 | 15282 | minor |
| 2465 | YES I found bad smells. The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14561 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2465 | 14561 | major |
| 1689 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Large class, 4. Primitive obsession, 5. Data clumps, 6. Temporary field, 7. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MapImageLayerTablesSample extends Application { private MapView mapView; private GraphicsOverlay graphicsOverlay; private ServiceFeatureTable commentsTable; private ListView commentsListView; /** * Starting point of this application. * * @param args arguments to this application. */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { // create a stack pane and application scene StackPane stackPane = new StackPane(); Scene scene = new Scene(stackPane); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); // size the stage and add a title stage.setTitle("Map Image Layer Tables Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(scene); stage.show(); // create a map with a basemap ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); // create and add a map image layer to the map // the map image layer contains a feature table with related spatial and non-spatial comment features ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer"); map.getOperationalLayers().add(imageLayer); // create a map view and set the map to it mapView = new MapView(); mapView.setMap(map); // create a graphics overlay to show the related spatial features in graphicsOverlay = new GraphicsOverlay(); mapView.getGraphicsOverlays().add(graphicsOverlay); // show the related graphics as cyan circles SimpleRenderer renderer = new SimpleRenderer(); renderer.setSymbol(new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF00FFFF, 14)); graphicsOverlay.setRenderer(renderer); // create a list view to show the non-spatial comment features commentsListView = new ListView<>(); commentsListView.setMaxSize(200.0, 150.0); // show the comments attribute of the feature in the list commentsListView.setCellFactory(listView -> new ListCell() { @Override protected void updateItem(Feature item, boolean empty) { super.updateItem(item, empty); if (item != null) { ArcGISFeature feature = (ArcGISFeature) item; setText((String) feature.getAttributes().get("comments")); } } }); // when a comment is selected, query its related spatial features and show the first result on the map commentsListView.getSelectionModel().selectedItemProperty().addListener(observable -> showRelatedRequests()); // when the layer is loaded, get the comment features imageLayer.addDoneLoadingListener(() -> { if (imageLayer.getLoadStatus() == LoadStatus.LOADED) { // zoom to the layer's extent mapView.setViewpoint(new Viewpoint(imageLayer.getFullExtent())); // get the comments feature table commentsTable = imageLayer.getTables().get(0); // create query parameters to get features that have non-empty comments QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause("requestid <> '' AND comments <> ''"); // query the comments table for features ListenableFuture featureQuery = commentsTable.queryFeaturesAsync(queryParameters); featureQuery.addDoneListener(() -> { try { // add the returned features to the list view FeatureQueryResult results = featureQuery.get(); for (Feature f : results) { commentsListView.getItems().addAll(f); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Error querying comment features"); } }); } else { new Alert(Alert.AlertType.ERROR, imageLayer.getLoadError().getMessage()).show(); } }); // add the mapview and controls to the stack pane stackPane.getChildren().addAll(mapView, commentsListView); StackPane.setAlignment(commentsListView, Pos.TOP_LEFT); StackPane.setMargin(commentsListView, new Insets(10, 0, 0, 10)); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } /** * Queries for spatial features related to the selected comment in the list view and shows the first result on the * map as a graphic. */ private void showRelatedRequests() { // clear any previous results graphicsOverlay.getGraphics().clear(); // get the selected comment feature from the list view Feature selectedCommentFeature = commentsListView.getSelectionModel().getSelectedItem(); if (selectedCommentFeature != null) { // get the relationships info between layers in the table ArcGISFeature feature = (ArcGISFeature) selectedCommentFeature; List relationshipInfos = commentsTable.getLayerInfo().getRelationshipInfos(); if (!relationshipInfos.isEmpty()) { // use the first relationship for the related query parameters RelationshipInfo commentsRelationshipInfo = relationshipInfos.get(0); RelatedQueryParameters relatedQueryParameters = new RelatedQueryParameters(commentsRelationshipInfo); relatedQueryParameters.setReturnGeometry(true); // query the table for related features using the parameters ListenableFuture> relatedFeaturesRequest = commentsTable .queryRelatedFeaturesAsync(feature, relatedQueryParameters); relatedFeaturesRequest.addDoneListener(() -> { try { // loop through the returned related features List results = relatedFeaturesRequest.get(); if (!results.isEmpty()) { RelatedFeatureQueryResult relatedResult = results.get(0); if (relatedResult.iterator().hasNext()) { // get the first related feature ArcGISFeature relatedFeature = (ArcGISFeature) relatedResult.iterator().next(); // load the feature and get its geometry to show as a graphic on the map relatedFeature.loadAsync(); relatedFeature.addDoneLoadingListener(() -> { if (relatedFeature.getLoadStatus() == LoadStatus.LOADED) { Point point = (Point) relatedFeature.getGeometry(); Graphic graphic = new Graphic(point); graphicsOverlay.getGraphics().add(graphic); // zoom to the graphic mapView.setViewpointCenterAsync(point, 40000); } }); } } else { new Alert(Alert.AlertType.INFORMATION, "No related features found").show(); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Failed to query relationships").show(); } }); } } } @Override public void stop() { // releases resources when the application closes if (mapView != null) { mapView.dispose(); } } } |
blob | Long method, 2 Feature envy, 3 Large class, 4 Primitive obsession, 5 Data clumps, 6 Temporary field, 7 Inappropriate intimacy | t | f | f | . Long method, 2. Feature envy, 3. Large class, 4. Primitive obsession, 5. Data clumps, 6. Temporary field, 7. Inappropriate intimacy | blob | 0 | 11694 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/imagelayers/map_image_layer_tables/MapImageLayerTablesSample.java/#L53-L234 | 2 | 1689 | 11694 | major |
| 1650 | YES I found bad smells the bad smells are: 1. Inconsistent naming conventions (e.g. getName and setName instead of getX and setX) 2. Lack of constructor with parameters, leading to an empty constructor 3. Use of raw types instead of specifying the type of elements in the Map 4. No validation or error handling in the setter methods 5. No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | Inconsistent naming conventions (eg getName and setName instead of getX and setX)2 Lack of constructor with parameters, leading to an empty constructor3 Use of raw types instead of specifying the type of elements in the Map4 No validation or error handling in the setter methods5 No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | t | f | f | . Inconsistent naming conventions (e.g. getName and setName instead of getX and setX)2. Lack of constructor with parameters, leading to an empty constructor3. Use of raw types instead of specifying the type of elements in the Map4. No validation or error handling in the setter methods5. No encapsulation of variables, as they are directly accessible through getters and setters without any validation or control over their values | data class | 0 | 11573 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 2 | 1650 | 11573 | minor |
| 113 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value @Wither(AccessLevel.PACKAGE) class CollectionJson { private String version; private @Nullable String href; private @JsonInclude(Include.NON_EMPTY) Links links; private @JsonInclude(Include.NON_EMPTY) List> items; private @JsonInclude(Include.NON_EMPTY) List queries; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonTemplate template; private @JsonInclude(Include.NON_NULL) @Nullable CollectionJsonError error; @JsonCreator CollectionJson(@JsonProperty("version") String version, // @JsonProperty("href") @Nullable String href, // @JsonProperty("links") @Nullable Links links, // @JsonProperty("items") @Nullable List> items, // @JsonProperty("queries") @Nullable List queries, // @JsonProperty("template") @Nullable CollectionJsonTemplate template, // @JsonProperty("error") @Nullable CollectionJsonError error) { this.version = version; this.href = href; this.links = links == null ? Links.NONE : links; this.items = items == null ? Collections.emptyList() : items; this.queries = queries == null ? Collections.emptyList() : queries; this.template = template; this.error = error; } CollectionJson() { this("1.0", null, Links.NONE, Collections.emptyList(), null, null, null); } @SafeVarargs final CollectionJson withItems(CollectionJsonItem... items) { return withItems(Arrays.asList(items)); } CollectionJson withItems(List> items) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withLinks(Link... links) { return withLinks(Links.of(links)); } CollectionJson withLinks(Links links) { return new CollectionJson<>(version, href, links, items, queries, template, error); } CollectionJson withOwnSelfLink() { String href = this.href; if (href == null) { return this; } return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links)); } boolean hasItems() { return !items.isEmpty(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1473 | https://github.com/spring-projects/spring-hateoas/blob/0e02d4f04117e03ab94110c9de09b2ac28d55599/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java/#L41-L107 | 2 | 113 | 1473 | minor |
| 1629 | { "message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Blob, Long Method | t | f | f | Blob, Long Method | data class | 0 | 11503 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 1629 | 11503 | critical |
| 4558 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
blob | Duplicate code2 Long method3 Feature envy | t | f | f | . Duplicate code2. Long method3. Feature envy | blob | 0 | 12116 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 2 | 4558 | 12116 | minor |
| 779 | {"message": "YES I found bad smells, the bad smells are: 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } } |
blob | 2. feature envy | t | t | f | 2. feature envy | blob | 0 | 7453 | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 | 1 | 779 | 7453 | minor |
| 1982 | YES I found bad smells the bad smells are: 1. Commented out code 2. Long method 3. Feature envy 4. Magic numbers 5. Unused variables 6. Unused imports 7. Excessive comments and documentation 8. Code duplication (the substituteArgs method is duplicated) 9. Lack of abstraction and encapsulation (substituteArgs method should be private and only used within the command class) 10. Not adhering to Single Responsibility Principle (the run method is doing too many different tasks) 11. Inefficient use of arrays (using arrays instead of more appropriate data structures) 12. Poor naming conventions (e.g. foreachArgs, token) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ForeachCommand extends Command { public static String[] foreachArgs = null; public ForeachCommand() { addCommand("foreach", "", "build up a list of elements to operate on "); addCommand("do", "", "repeat a command for each element in the list"); } public void run(String command, final String[] args, final Context context, final PrintStream out) throws DDRInteractiveCommandException { if (command.equals("!do")) { boolean echo = false; boolean quiet = false; String token = null; int commandIndex = 0; while (commandIndex < args.length) { if (args[commandIndex].equals("help")) { out.println("The !do command is used to repeat a command on the elements gathered by the !foreach command."); out.println("Syntax: !do [echo] [quiet] [token=] [args]"); out.println(); out.println("\techo\t\tOutput each command before it is run."); out.println("\tquiet\t\tSuppress delimiters between command outputs."); out.println("\ttoken=\tSpecify a substitution token. Occurrencs of this string in the args will be replaced by the current element."); return; } else if (args[commandIndex].equals("echo")) { echo = true; commandIndex += 1; } else if (args[commandIndex].equals("quiet")) { quiet = true; commandIndex += 1; } else if (args[commandIndex].startsWith("token=")) { token = args[commandIndex].substring("token=".length()); commandIndex += 1; } else { break; } } if (commandIndex >= args.length) { out.println("The do command requires another command to repeat."); return; } if ((null == foreachArgs) || (0 == foreachArgs.length)) { out.println("Element list is empty. Use the foreach command to populate it."); return; } for (int i = 0; i < foreachArgs.length; i++) { if (!quiet && (i > 0)) { out.println("========================================"); } try { String[] newArgs; if (null == token) { newArgs = substituteArgs(args, commandIndex, i); } else { newArgs = substituteArgs(args, commandIndex, i, token); } if (echo) { System.out.println("> " + args[commandIndex] + " " + Arrays.toString(newArgs)); } CommandParser commandParser = new CommandParser(args[commandIndex], newArgs); context.execute(commandParser, out); } catch (ParseException e) { e.printStackTrace(out); } catch (Throwable th) { out.println("Exception while executing " + args[commandIndex] + " " + foreachArgs[i]); th.printStackTrace(out); } } } else if(command.equals("!foreach")) { if (args.length > 0) { out.println("The !foreach command takes no arguments, but will read lines from the console until it encounters a blank line."); out.println("These lines can then be used as arguments to commands specified using !do."); return; } ArrayList lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (0 == line.length()) { break; } else { lines.add(line); } } // split by , String[] newArgs = new String[lines.size()]; lines.toArray(newArgs); foreachArgs = newArgs; } } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex) { /* Concatenate: * */ String[] newArgs = new String[args.length - commandIndex]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); newArgs[newArgs.length - 1] = foreachArgs[foreachIndex]; return newArgs; } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex, String token) { /* Concatenate: * * Replacing any occurence of token with */ String[] newArgs = new String[args.length - commandIndex - 1]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); for (int i = 0; i < newArgs.length; i++) { newArgs[i] = newArgs[i].replace(token, foreachArgs[foreachIndex]); } return newArgs; } } |
blob | Commented out code2 Long method3 Feature envy4 Magic numbers5 Unused variables6 Unused imports7 Excessive comments and documentation8 Code duplication (the substituteArgs method is duplicated)9 Lack of abstraction and encapsulation (substituteArgs method should be private and only used within the command class) | t | f | f | . Commented out code2. Long method3. Feature envy4. Magic numbers5. Unused variables6. Unused imports7. Excessive comments and documentation8. Code duplication (the substituteArgs method is duplicated)9. Lack of abstraction and encapsulation (substituteArgs method should be private and only used within the command class) | blob | 0 | 12643 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/tools/ddrinteractive/commands/ForeachCommand.java/#L37-L165 | 2 | 1982 | 12643 | major |
| 437 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder(float k1, float b) { this.similarity = new BM25Similarity(k1, b); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4292 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L78-L80 | 2 | 437 | 4292 | minor |
| 75 | { "message": "YES, I found bad smells", "bad smells are": [ "Use of raw type", "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class State { public Map properties = new HashMap(); public Map array_properties = new HashMap(); } |
data class | use of raw type, long method | t | t | f | use of raw type, long method | data class | 0 | 1125 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/intellij/ApplicationSettings.java/#L58-L61 | 2 | 75 | 1125 | major |
| 2636 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } } |
blob | long method | t | t | f | long method | blob | 0 | 15118 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 | 1 | 2636 | 15118 | minor |
| 1368 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 10790 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 1 | 1368 | 10790 | minor |
| 1871 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12249 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 1871 | 12249 | minor |
| 350 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 3597 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 2 | 350 | 3597 | major |
| 323 | YES I found bad smells The bad smells are: 1. Long class 2. Violation of encapsulation 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
blob | Long class2 Violation of encapsulation3 Feature envy | t | f | f | . Long class2. Violation of encapsulation3. Feature envy | blob | 0 | 3320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 2 | 323 | 3320 | major |
| 2686 | { "YES I found bad smells": true, "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 15279 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 | 2 | 2686 | 15279 | minor |
| 2771 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | long method | t | t | f | long method | data class | 0 | 1068 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 2771 | 1068 | major |
| 2546 | YES I found bad smells 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
feature envy | t | f | f | feature envy | 0 | 14791 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 2546 | 14791 | major | ||
| 1713 | {"response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11775 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 1 | 1713 | 11775 | major |
| 1601 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11429 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 1601 | 11429 | minor |
| 219 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PTransformReplacements { /** * Gets the singleton input of an {@link AppliedPTransform}, ignoring any additional inputs * returned by {@link PTransform#getAdditionalInputs()}. */ public static PCollection getSingletonMainInput( AppliedPTransform, ?, ?> application) { return getSingletonMainInput( application.getInputs(), application.getTransform().getAdditionalInputs().keySet()); } private static PCollection getSingletonMainInput( Map, PValue> inputs, Set> ignoredTags) { PCollection mainInput = null; for (Map.Entry, PValue> input : inputs.entrySet()) { if (!ignoredTags.contains(input.getKey())) { checkArgument( mainInput == null, "Got multiple inputs that are not additional inputs for a " + "singleton main input: %s and %s", mainInput, input.getValue()); checkArgument( input.getValue() instanceof PCollection, "Unexpected input type %s", input.getValue().getClass()); mainInput = (PCollection) input.getValue(); } } checkArgument( mainInput != null, "No main input found in inputs: Inputs %s, Side Input tags %s", inputs, ignoredTags); return mainInput; } public static PCollection getSingletonMainOutput( AppliedPTransform, ? extends PTransform>> transform) { return (PCollection) Iterables.getOnlyElement(transform.getOutputs().values()); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 2390 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformReplacements.java/#L32-L73 | 2 | 219 | 2390 | minor |
| 320 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 3293 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 1 | 320 | 3293 | minor |
| 1455 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11008 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 | 1 | 1455 | 11008 | major |
| 2357 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3. Speculative generality: abstract class is unnecessary, 4. Inconsistent formatting, 5. Inappropriate naming, 6. Feature envy: inner class accessing data from outer class, 7. Inappropriate use of annotations, 8. Coupled structure: subclasses have nearly identical structure, 9. Inappropriate use of inheritance, 10. Inappropriate comments: comments are not useful and add clutter to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | Long method, 2 Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3 Speculative generality: abstract class is unnecessary, 4 Inconsistent formatting, 5 Inappropriate naming, 6 Feature envy: inner class accessing data from outer class, 7 Inappropriate use of annotations, 8 Coupled structure: subclasses have nearly identical structure, 9 Inappropriate use of inheritance, | t | f | f | . Long method, 2. Feature envy: methods in subclasses of PendingActionNotificationResponse are accessing data from the superclass instead of using their own data, 3. Speculative generality: abstract class is unnecessary, 4. Inconsistent formatting, 5. Inappropriate naming, 6. Feature envy: inner class accessing data from outer class, 7. Inappropriate use of annotations, 8. Coupled structure: subclasses have nearly identical structure, 9. Inappropriate use of inheritance, | data class | 0 | 14232 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 2 | 2357 | 14232 | major |
| 378 | { "message": "YES I found bad smells", "detectedBadSmells": [ "Long Method", "Feature Envy" ], "theBadSmellsAre": "1. Long Method, 2. Feature Envy" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
feature envy | Incoherent response format, very different from what was expected. | f | f | f | false | 0 | 3904 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 378 | 3904 | major | |
| 1083 | YES I found bad smells. The bad smells are: 1. Long class 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long class2 Long method3 Feature envy | t | f | f | . Long class2. Long method3. Feature envy | data class | 0 | 9689 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 1083 | 9689 | minor |
| 1769 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 11918 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 1769 | 11918 | minor |
| 2213 | YES, I found bad smellsthe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13526 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 2 | 2213 | 13526 | minor |
| 856 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic number, 3.Long parameter list, 4.Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Validator childNodeChanged(String name, NodeState before, NodeState after) throws CommitFailedException { Tree beforeTree = (parentBefore == null) ? null : parentBefore.getChild(name); Tree afterTree = parentAfter.getChild(name); if (isTokenTree(beforeTree) || isTokenTree(afterTree)) { validateTokenTree(afterTree); } else if (isTokensParent(beforeTree) || isTokensParent(afterTree)) { validateTokensParent(afterTree); } return new VisibleValidator(new TokenValidator(beforeTree, afterTree, commitInfo), true, true); } |
feature envy | Long method, 2Magic number, 3Long parameter list, 4Inappropriate intimacy | t | f | f | .Long method, 2.Magic number, 3.Long parameter list, 4.Inappropriate intimacy | feature envy | 0 | 7885 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/security/authentication/token/TokenValidatorProvider.java/#L130-L142 | 2 | 856 | 7885 | major |
| 1721 | {"answer":"YES I found bad smells","the bad smells are:":["1. Long method","2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 11796 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 1 | 1721 | 11796 | critical |
| 107 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Customer583Repository extends CrudRepository { List findByLastName(String lastName); } |
data class | 1. blob, 2. long method | t | t | f | 1. blob, 2. long method | data class | 0 | 1412 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/repo/Customer583Repository.java/#L9-L12 | 1 | 107 | 1412 | critical |
| 194 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2230 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 | 1 | 194 | 2230 | minor |
| 2251 | YES I found bad smells the bad smells are: 1.Unused import, 2.Long method, 3.Magic number, 4.Inappropriate naming, 5.Unnecessary suppression, 6.Inconsistent indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | Unused import, 2Long method, 3Magic number, 4Inappropriate naming, 5Unnecessary suppression, 6Inconsistent indentation | t | f | f | .Unused import, 2.Long method, 3.Magic number, 4.Inappropriate naming, 5.Unnecessary suppression, 6.Inconsistent indentation | data class | 0 | 13674 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 2 | 2251 | 13674 | minor |
| 4574 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12157 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 4574 | 12157 | minor | ||
| 2647 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 15160 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 2647 | 15160 | major |
| 3914 | { "YES I found bad smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } } |
blob | long method | t | t | f | long method | blob | 0 | 10245 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 | 1 | 3914 | 10245 | major |
| 2250 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Hard-coded values 5. Lack of parameterization 6. Lack of abstraction and encapsulation 7. Use of raw types 8. Use of deprecated methods 9. Excessive use of conditional statements 10. Poor method and variable naming 11. Lack of comments and documentation 12. Poor error handling and exception handling 13. Unnecessary variables and loops. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
data class | Long method2 Feature envy3 Duplicate code4 Hard-coded values5 Lack of parameterization6 Lack of abstraction and encapsulation7 Use of raw types8 Use of deprecated methods9 Excessive use of conditional statements | t | f | f | . Long method2. Feature envy3. Duplicate code4. Hard-coded values5. Lack of parameterization6. Lack of abstraction and encapsulation7. Use of raw types8. Use of deprecated methods9. Excessive use of conditional statements | data class | 0 | 13669 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 2 | 2250 | 13669 | minor |
| 3787 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ @Immutable public static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; @Immutable private static final TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private InternalCache cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DistributionManager dm; /** * Command Service */ private OnlineCommandProcessor commandProcessor; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(InternalCache cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if (dm instanceof ClusterDistributionManager) { ClusterDistributionManager distManager = (ClusterDistributionManager) system.getDistributionManager(); this.redundancyZone = distManager .getRedundancyZone(cache.getInternalDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandProcessor = new OnlineCommandProcessor(system.getProperties(), cache.getSecurityService(), cache); } catch (Exception e) { commandServiceInitError = e.getMessage(); logger.info(LogMarker.CONFIG_MARKER, "Command processor could not be initialized. {}", e.getMessage()); } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ignore) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); // Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); // Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getInternalResourceManager().getStats(); } public MemberMBeanBridge() { this.monitor = new MBeanStatsMonitor("MemberMXBeanMonitor"); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor("GCStatsMonitor"); this.vmStatsMonitor = new VMStatsMonitor("VMStatsMonitor"); this.systemStatsMonitor = new MBeanStatsMonitor("SystemStatsManager"); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = this.cache.getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system.getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;// @TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = this.cache.getOffHeapStore(); if ((null != allocator)) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if (null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats) { diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats) { diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } InternalRegion internalRegion = (InternalRegion) region; addLRUStats(internalRegion.getEvictionStatistics()); DiskRegion dr = internalRegion.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(Statistics lruStats) { if (lruStats != null) { regionMonitor.addStatisticsToMonitor(lruStats); } } public void addDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region) { if (region.getAttributes().getPartitionAttributes() != null) { removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; removeLRUStats(l.getEvictionStatistics()); DiskRegion dr = l.getDiskRegion(); if (dr != null) { for (DirectoryHolder dh : dr.getDirectories()) { removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(Statistics statistics) { if (statistics != null) { regionMonitor.removeLRUStatistics(statistics); } } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock) { if (!lockStatsAdded) { DLockStats stats = (DLockStats) lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats) { monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if (samplerStats != null) { systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats() { VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50) { VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0) { for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor() { monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats() { createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate(StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate(StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate(StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate(StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate(StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate(StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency(StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency(StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency(StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency(StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency(StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency(StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency(StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency(StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency(StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate(StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate(StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate(StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); long gcTimeMillis = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); // Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in java.lang.management.OperatingSystemMXBean It has to be cast * to com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic call so that Java * platform will take care of the details in a native manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME).longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute(osObjectName, "CommittedVirtualMemorySize"); } catch (Exception ignore) { committedVirtualMemorySize = -1; } // If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception ignore) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception ignore) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception ignore) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get(StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception ignore) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(ex.getMessage(), ex); } } return metrics; } /** * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { List compactedStores = new ArrayList(); if (cache != null && !cache.isClosed()) { for (DiskStore store : this.cache.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(((DiskStoreImpl) store).getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned indicates whether to show the disk belonging to any particular region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { String[] retStr = null; Collection diskCollection = null; if (includeRegionOwned) { diskCollection = this.cache.listDiskStoresIncludingRegionOwned(); } else { diskCollection = this.cache.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return log of the member. */ public String fetchLog(int numLines) { if (numLines > ManagementConstants.MAX_SHOW_LOG_LINES) { numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if (numLines == 0 || numLines < 0) { numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; if (sys.getLogFile().isPresent()) { LogFile logFile = sys.getLogFile().get(); childTail = BeanUtilFuncs.tailSystemLog(logFile.getChildLogFile(), numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = "No log file was specified in the configuration, messages will be directed to stdout."; } } else { throw new IllegalStateException( "TailLogRequest/Response processed in application vm with shared logging. This would occur if there is no 'log-file' defined."); } } catch (IOException e) { logger.warn("Error occurred while reading system log:", e); mainTail = ""; } if (childTail == null && mainTail == null) { return "No log file configured, log messages will be directed to stdout."; } else { StringBuilder result = new StringBuilder(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append(getLineSeparator()) .append("-------------------- tail of child log --------------------") .append(getLineSeparator()); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by FunctionService. Might cause * problems in cleaning up function related resources. Aggregate bean DistributedSystemMBean will * have to depend on GemFire messages to decide whether all the members have been shutdown or not * before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new LoggingThread("Shutdown member", false, () -> { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException ignore) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } }); t.start(); } } /** * @return The name for this member. */ public String getName() { return name; } /** * @return The ID for this member. */ public String getId() { return id; } /** * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not * limited to: Locators, Managers, Cache Servers and so on. * * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); return memHeap.getUsed(); } /** * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList thrdStr = new ArrayList(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * @return list of regions */ public String[] getListOfRegions() { Set listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (InternalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * @return root region names */ public String[] getRootRegionNames() { Set> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionNames = new String[listOfRootRegions.size()]; int j = 0; for (Region region : listOfRootRegions) { regionNames[j] = region.getFullPath(); j++; } return regionNames; } return ManagementConstants.NO_DATA_STRING; } /** * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * @return true if member contains one locator. From 7.0 only locator can be hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * @return true if the Federating Manager Thread is running */ public boolean isManager() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManager(); } catch (Exception ignore) { return false; } } /** * Returns true if the manager has been created. Note it does not need to be running so this * method can return true when isManager returns false. * * @return true if the manager has been created. */ public boolean isManagerCreated() { if (this.cache == null || this.cache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch (Exception ignore) { return false; } } /** * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED).intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgress() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME).longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING).intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information if it's non-empty. * Result returned is in a JSON format. * * @param commandString command string to be processed * @param env environment information to be used for processing the command * @param stagedFilePaths list of local files to be deployed * @return result of the processing the given command string. */ public String processCommand(String commandString, Map env, List stagedFilePaths) { if (commandProcessor == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: " + commandServiceInitError); } Object result = commandProcessor.executeCommand(commandString, env, stagedFilePaths); if (result instanceof CommandResult) { return CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); } else { return CommandResponseBuilder.createCommandResponseJson(getMember(), (ResultModel) result); } } public long getTotalDiskUsage() { return regionMonitor.getDiskSpace(); } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception ignore) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { objects = stats.getObjects(); } return objects; } /** * @deprecated Please use {@link #getOffHeapFreeMemory()} instead. */ @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } /** * @deprecated Please use {@link #getOffHeapUsedMemory()} instead. */ @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if (null != stats) { compactionTime = stats.getDefragmentationTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if (null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } public String getReleaseVersion() { return GemFireVersion.getGemFireVersion(); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java/#L119-L1725 | 1 | 3787 | 9539 | minor |
| 1256 | {"message": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 10494 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 | 2 | 1256 | 10494 | minor |
| 1866 | YES I found bad smells the bad smells are: 1. Long class 2. Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out") 3. Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long class2 Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out")3 Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | t | f | f | . Long class2. Magic number (binary = false, charset = "UTF-8", dir = "/tmp/xd/output/", suffix = "out")3. Feature envy (getName(), setName(), getDirExpression(), setDirExpression()) | data class | 0 | 12238 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 1866 | 12238 | critical |
| 1977 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12630 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 1977 | 12630 | minor |
| 1741 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11842 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 | 1 | 1741 | 11842 | major |
| 168 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; } |
blob | Not specified | f | f | f | false | 0 | 2029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 | 2 | 168 | 2029 | minor | |
| 482 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void removePipeline(Pipeline pipeline) { for (DatanodeDetails details : pipeline.getNodes()) { UUID dnId = details.getUuid(); dn2ObjectMap.computeIfPresent(dnId, (k, v) -> { v.remove(pipeline.getId()); return v; }); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 4708 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/states/Node2PipelineMap.java/#L67-L76 | 2 | 482 | 4708 | minor |
| 802 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
data class | long method | t | t | f | long method | data class | 0 | 7592 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 1 | 802 | 7592 | minor |
| 239 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
blob | data class | t | t | f | data class | blob | 0 | 2614 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 239 | 2614 | minor |
| 1501 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 11134 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 1501 | 11134 | minor |
| 229 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 2506 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 2 | 229 | 2506 | minor |
| 2456 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14524 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 2 | 2456 | 14524 | major |
| 567 | YES, I found bad smells. The bad smells are: 1. Comments that are not descriptive or provide enough information on the code's purpose. 2. Variables such as writerName, readerName, outputName, and exportString that are not meaningful or clear. 3. Methods that are not properly named or do not have clear and descriptive purpose. 4. Lack of encapsulation - Variables and methods should be specifically declared as private or public. 5. Lack of proper error handling - The code does not have a proper mechanism to handle errors or exceptions. 6. Long class - The class contains multiple methods and has a large number of lines of code. 7. Feature envy - The class has a strong dependency on the IOService, which could be a separate class. 8. Magic numbers - The code contains arbitrary numbers without clear explanations of their purpose. 9. Poor use of conditionals - The code uses "==" to compare strings instead of using the ".equals" method. 10. Dead code - The code contains unused variables or methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } } |
blob | Comments that are not descriptive or provide enough information on the code's purpose2 Variables such as writerName, readerName, outputName, and exportString that are not meaningful or clear3 Methods that are not properly named or do not have clear and descriptive purpose4 Lack of encapsulation - Variables and methods should be specifically declared as private or public5 Lack of proper error handling - The code does not have a proper mechanism to handle errors or exceptions6 Long class - The class contains multiple methods and has a large number of lines of code7 Feature envy - The class has a strong dependency on the IOService, which could be a separate class8 Magic numbers - The code contains arbitrary numbers without clear explanations of their purpose9 Poor use of conditionals - The code uses "==" to compare strings instead of using the "equals" method | t | f | f | . Comments that are not descriptive or provide enough information on the code's purpose.2. Variables such as writerName, readerName, outputName, and exportString that are not meaningful or clear.3. Methods that are not properly named or do not have clear and descriptive purpose.4. Lack of encapsulation - Variables and methods should be specifically declared as private or public.5. Lack of proper error handling - The code does not have a proper mechanism to handle errors or exceptions.6. Long class - The class contains multiple methods and has a large number of lines of code.7. Feature envy - The class has a strong dependency on the IOService, which could be a separate class.8. Magic numbers - The code contains arbitrary numbers without clear explanations of their purpose.9. Poor use of conditionals - The code uses "==" to compare strings instead of using the ".equals" method. | blob | 0 | 5724 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 | 2 | 567 | 5724 | minor |
| 2377 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 14326 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 2377 | 14326 | minor |
| 248 | {"response": "YES I found bad smells", "the bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Service public class DepositAccountAssembler { private final PlatformSecurityContext context; private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsHelper savingsHelper; private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final StaffRepositoryWrapper staffRepository; private final FixedDepositProductRepository fixedDepositProductRepository; private final RecurringDepositProductRepository recurringDepositProductRepository; private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final SavingsAccountChargeAssembler savingsAccountChargeAssembler; private final FromJsonHelper fromApiJsonHelper; private final DepositProductAssembler depositProductAssembler; private final PaymentDetailAssembler paymentDetailAssembler; @Autowired public DepositAccountAssembler(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final ClientRepositoryWrapper clientRepository, final GroupRepositoryWrapper groupRepository, final StaffRepositoryWrapper staffRepository, final FixedDepositProductRepository fixedDepositProductRepository, final SavingsAccountRepositoryWrapper savingsAccountRepository, final SavingsAccountChargeAssembler savingsAccountChargeAssembler, final FromJsonHelper fromApiJsonHelper, final DepositProductAssembler depositProductAssembler, final RecurringDepositProductRepository recurringDepositProductRepository, final AccountTransfersReadPlatformService accountTransfersReadPlatformService, final PlatformSecurityContext context, final PaymentDetailAssembler paymentDetailAssembler) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.staffRepository = staffRepository; this.fixedDepositProductRepository = fixedDepositProductRepository; this.savingsAccountRepository = savingsAccountRepository; this.savingsAccountChargeAssembler = savingsAccountChargeAssembler; this.fromApiJsonHelper = fromApiJsonHelper; this.depositProductAssembler = depositProductAssembler; this.recurringDepositProductRepository = recurringDepositProductRepository; this.savingsHelper = new SavingsHelper(accountTransfersReadPlatformService); this.context = context; this.paymentDetailAssembler = paymentDetailAssembler; } /** * Assembles a new {@link SavingsAccount} from JSON details passed in * request inheriting details where relevant from chosen * {@link SavingsProduct}. */ public SavingsAccount assembleFrom(final JsonCommand command, final AppUser submittedBy, final DepositAccountType depositAccountType) { final JsonElement element = command.parsedJson(); final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); SavingsProduct product = null; if (depositAccountType.isFixedDeposit()) { product = this.fixedDepositProductRepository.findOne(productId); if (product == null) { throw new FixedDepositProductNotFoundException(productId); } } else if (depositAccountType.isRecurringDeposit()) { product = this.recurringDepositProductRepository.findOne(productId); if (product == null) { throw new RecurringDepositProductNotFoundException(productId); } } if (product == null) { throw new SavingsProductNotFoundException(productId); } Client client = null; Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; } if (group != null && client != null) { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } accountType = AccountType.JLG; if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); } else { interestRate = product.nominalAnnualInterestRate(); } SavingsCompoundingInterestPeriodType interestCompoundingPeriodType = null; final Integer interestPeriodTypeValue = command.integerValueOfParameterNamed(interestCompoundingPeriodTypeParamName); if (interestPeriodTypeValue != null) { interestCompoundingPeriodType = SavingsCompoundingInterestPeriodType.fromInt(interestPeriodTypeValue); } else { interestCompoundingPeriodType = product.interestCompoundingPeriodType(); } SavingsPostingInterestPeriodType interestPostingPeriodType = null; final Integer interestPostingPeriodTypeValue = command.integerValueOfParameterNamed(interestPostingPeriodTypeParamName); if (interestPostingPeriodTypeValue != null) { interestPostingPeriodType = SavingsPostingInterestPeriodType.fromInt(interestPostingPeriodTypeValue); } else { interestPostingPeriodType = product.interestPostingPeriodType(); } SavingsInterestCalculationType interestCalculationType = null; final Integer interestCalculationTypeValue = command.integerValueOfParameterNamed(interestCalculationTypeParamName); if (interestCalculationTypeValue != null) { interestCalculationType = SavingsInterestCalculationType.fromInt(interestCalculationTypeValue); } else { interestCalculationType = product.interestCalculationType(); } SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = command .integerValueOfParameterNamed(interestCalculationDaysInYearTypeParamName); if (interestCalculationDaysInYearTypeValue != null) { interestCalculationDaysInYearType = SavingsInterestCalculationDaysInYearType.fromInt(interestCalculationDaysInYearTypeValue); } else { interestCalculationDaysInYearType = product.interestCalculationDaysInYearType(); } BigDecimal minRequiredOpeningBalance = null; if (command.parameterExists(minRequiredOpeningBalanceParamName)) { minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); } else { minRequiredOpeningBalance = product.minRequiredOpeningBalance(); } Integer lockinPeriodFrequency = null; if (command.parameterExists(lockinPeriodFrequencyParamName)) { lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); } else { lockinPeriodFrequency = product.lockinPeriodFrequency(); } SavingsPeriodFrequencyType lockinPeriodFrequencyType = null; if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { Integer lockinPeriodFrequencyTypeValue = null; lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); if (lockinPeriodFrequencyTypeValue != null) { lockinPeriodFrequencyType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); } } else { lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); } boolean iswithdrawalFeeApplicableForTransfer = false; if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element, product.currency().getCode()); DepositAccountInterestRateChart accountChart = null; InterestRateChart productChart = null; if (command.parameterExists(chartIdParamName)) { Long chartId = command.longValueOfParameterNamed(chartIdParamName); productChart = product.findChart(chartId); } else { productChart = product.applicableChart(submittedOnDate); } if (productChart != null) { accountChart = DepositAccountInterestRateChart.from(productChart); } boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); if(withHoldTax && product.getTaxGroup() == null){ throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } SavingsAccount account = null; if (depositAccountType.isFixedDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((FixedDepositProduct) product).depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); FixedDepositAccount fdAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(fdAccount); fdAccount.validateDomainRules(); account = fdAccount; } else if (depositAccountType.isRecurringDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((RecurringDepositProduct) product) .depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); final DepositProductRecurringDetail prodRecurringDetail = ((RecurringDepositProduct) product).depositRecurringDetail(); final DepositAccountRecurringDetail accountRecurringDetail = this.assembleAccountRecurringDetail(command, prodRecurringDetail.recurringDetail()); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountRecurringDetail, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(rdAccount); accountRecurringDetail.updateAccountReference(rdAccount); rdAccount.validateDomainRules(); account = rdAccount; } if (account != null) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(), depositAccountType.resourceName()); } return account; } public SavingsAccount assembleFrom(final Long savingsId, DepositAccountType depositAccountType) { final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId, depositAccountType); account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure .depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, productPreClosure); final DepositTermDetail updatedProductTerm = this.depositProductAssembler.assembleDepositTermDetail(command, productTerm); final BigDecimal depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName); final Integer depositPeriod = command.integerValueOfParameterNamed(depositPeriodParamName); final Integer depositPeriodFrequencyId = command.integerValueOfParameterNamed(depositPeriodFrequencyIdParamName); final SavingsPeriodFrequencyType depositPeriodFrequency = SavingsPeriodFrequencyType.fromInt(depositPeriodFrequencyId); final SavingsAccount account = null; final LocalDate expectedFirstDepositOnDate = command.localDateValueOfParameterNamed(expectedFirstDepositOnDateParamName); final Boolean trasferInterest = command.booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName); // calculate maturity amount final BigDecimal maturityAmount = null;// calculated and updated in // account final LocalDate maturityDate = null;// calculated and updated in account final DepositAccountOnClosureType accountOnClosureType = null; return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest); } public DepositAccountRecurringDetail assembleAccountRecurringDetail(final JsonCommand command, final DepositRecurringDetail prodRecurringDetail) { final BigDecimal recurringDepositAmount = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); boolean isMandatoryDeposit; boolean allowWithdrawal; boolean adjustAdvanceTowardsFuturePayments; boolean isCalendarInherited; if (command.parameterExists(isMandatoryDepositParamName)) { isMandatoryDeposit = command.booleanObjectValueOfParameterNamed(isMandatoryDepositParamName); } else { isMandatoryDeposit = prodRecurringDetail.isMandatoryDeposit(); } if (command.parameterExists(allowWithdrawalParamName)) { allowWithdrawal = command.booleanObjectValueOfParameterNamed(allowWithdrawalParamName); } else { allowWithdrawal = prodRecurringDetail.allowWithdrawal(); } if (command.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName)) { adjustAdvanceTowardsFuturePayments = command.booleanObjectValueOfParameterNamed(adjustAdvanceTowardsFuturePaymentsParamName); } else { adjustAdvanceTowardsFuturePayments = prodRecurringDetail.adjustAdvanceTowardsFuturePayments(); } if (command.parameterExists(isCalendarInheritedParamName)) { isCalendarInherited = command.booleanObjectValueOfParameterNamed(isCalendarInheritedParamName); } else { isCalendarInherited = false; } final DepositRecurringDetail depositRecurringDetail = DepositRecurringDetail.createFrom(isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments); final DepositAccountRecurringDetail depositAccountRecurringDetail = DepositAccountRecurringDetail.createNew(recurringDepositAmount, depositRecurringDetail, null, isCalendarInherited); return depositAccountRecurringDetail; } public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = this.fromApiJsonHelper.parse(json); final Collection savingsAccountTransactions = new ArrayList<>(); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale); if (element.isJsonObject()) { if (topLevelJsonElement.has(bulkSavingsDueTransactionsParamName) && topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); } final SavingsAccountTransactionDTO savingsAccountTransactionDTO = new SavingsAccountTransactionDTO(formatter, transactionDate, dueAmount, detail, new Date(), savingsId, user, depositAccountType); savingsAccountTransactions.add(savingsAccountTransactionDTO); } } } return savingsAccountTransactions; } private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { user = this.context.getAuthenticatedUserIfPresent(); } return user; } } |
blob | long method | t | t | f | long method | blob | 0 | 2661 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java/#L107-L472 | 2 | 248 | 2661 | major |
| 1212 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Violation of Single Responsibility Principle (SRP) 6. Overuse of modifiers (e.g. final, volatile) 7. Inadequate exception handling (e.g. thrown but not caught) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | Long method2 Feature envy3 Duplicate code4 Inconsistent naming conventions5 Violation of Single Responsibility Principle (SRP) 6 Overuse of modifiers (eg final, volatile) 7 Inadequate exception handling (eg thrown but not caught) | t | f | f | . Long method2. Feature envy3. Duplicate code4. Inconsistent naming conventions5. Violation of Single Responsibility Principle (SRP) 6. Overuse of modifiers (e.g. final, volatile) 7. Inadequate exception handling (e.g. thrown but not caught) | data class | 0 | 10312 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 2 | 1212 | 10312 | minor |
| 1676 | {"response": "YES I found bad smells", "bad smells are": ["1. Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 11645 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 1676 | 11645 | minor |
| 617 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 6181 | https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 | 2 | 617 | 6181 | minor |
| 5084 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14204 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 5084 | 14204 | major |
| 748 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 7018 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 2 | 748 | 7018 | major |
| 312 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onNodeSelected(TreeNodeElement node, SignalEvent event) { getSelectionModel().setTreeActive(true); selectNode(node.getData(), event, true); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 3213 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/tree/Tree.java/#L732-L736 | 2 | 312 | 3213 | critical |
| 1958 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12570 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 2 | 1958 | 12570 | minor |
| 867 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7941 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 2 | 867 | 7941 | minor |
| 740 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class getJobSummary_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getJobSummary_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getJobSummary_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 6974 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/ReadOnlyScheduler.java/#L3175-L3220 | 1 | 740 | 6974 | minor |
| 1578 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number 3. Comments 4. Not following naming conventions 5. Feature envy (MetricsAssignmentManagerSourceImpl class referencing to BaseSourceImpl methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
blob | Long method2 Magic number3 Comments4 Not following naming conventions5 Feature envy (MetricsAssignmentManagerSourceImpl class referencing to BaseSourceImpl methods) | t | f | f | . Long method2. Magic number3. Comments4. Not following naming conventions5. Feature envy (MetricsAssignmentManagerSourceImpl class referencing to BaseSourceImpl methods) | blob | 0 | 11354 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 2 | 1578 | 11354 | minor |
| 456 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Shotgun surgery, 4. Primitive obsession, 5. Data clumps, 6. Inappropriate intimacy, 7. Dead code, 8. Duplication, 9. Lazy class, 10. Speculative generality | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
blob | Long method, 2 Feature envy, 3 Shotgun surgery, 4 Primitive obsession, 5 Data clumps, 6 Inappropriate intimacy, 7 Dead code, 8 Duplication, 9 Lazy class, | t | f | f | . Long method, 2. Feature envy, 3. Shotgun surgery, 4. Primitive obsession, 5. Data clumps, 6. Inappropriate intimacy, 7. Dead code, 8. Duplication, 9. Lazy class, | blob | 0 | 4453 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 456 | 4453 | minor |
| 1021 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9351 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 1 | 1021 | 9351 | critical |
| 314 | Note:YES I found bad smells the bad smells are: 1. Inconsistent indentation and formatting 2. Misleading variable names 3. Unclear hierarchy and purpose of classes and methods 4. Poor encapsulation of the side input feature 5. Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class 6. Potential feature envy in the setSideInput() method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Inconsistent indentation and formatting2 Misleading variable names3 Unclear hierarchy and purpose of classes and methods4 Poor encapsulation of the side input feature5 Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class6 Potential feature envy in the setSideInput() method | t | f | f | . Inconsistent indentation and formatting2. Misleading variable names3. Unclear hierarchy and purpose of classes and methods4. Poor encapsulation of the side input feature5. Possible violation of the Single Responsibility Principle (SRP) by having multiple responsibilities in one class6. Potential feature envy in the setSideInput() method | data class | 0 | 3227 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 314 | 3227 | major |
| 357 | {"response": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ConfigFilePropertySource extends FilePropertySource { private IFile file; public ConfigFilePropertySource(IFile file) { super(file); this.file = file; } @Override public String toString() { return file.getFullPath().toString(); } } |
data class | f | f | f | data class | 0 | 3677 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.beans.ui/src/org/springframework/ide/eclipse/beans/ui/model/properties/ChildBeanProperties.java/#L154-L166 | 1 | 357 | 3677 | major | ||
| 332 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract static class Builder> { protected abstract T self(); protected Long id; protected String name; protected String description; /** * @see Option#getId() */ public T id(Long id) { this.id = id; return self(); } /** * @see Option#getName() */ public T name(String name) { this.name = name; return self(); } /** * @see Option#getDescription() */ public T description(String description) { this.description = description; return self(); } public Option build() { return new Option(id, name, description); } public T fromOption(Option in) { return this .id(in.getId()) .name(in.getName()) .description(in.getDescription()); } } |
data class | long method | t | t | f | long method | data class | 0 | 3402 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Option.java/#L48-L89 | 1 | 332 | 3402 | major |
| 1971 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Message chain, 4.Lazy class, 5.Magic number, 6.Unused code, 7.Commented-out code, 8.Data class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } } |
blob | Long method, 2Feature envy, 3Message chain, 4Lazy class, 5Magic number, 6Unused code, 7Commented-out code, 8Data class | t | f | f | .Long method, 2.Feature envy, 3.Message chain, 4.Lazy class, 5.Magic number, 6.Unused code, 7.Commented-out code, 8.Data class. | blob | 0 | 12608 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 | 2 | 1971 | 12608 | major |
| 2561 | {"response": "YES I found bad smells the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 14841 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 1 | 2561 | 14841 | minor |
| 2169 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 13355 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 2169 | 13355 | major |
| 3215 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | \n1. long method | t | t | f | \\n1. long method | data class | 0 | 5113 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 1 | 3215 | 5113 | minor |
| 1487 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 11103 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 | 1 | 1487 | 11103 | minor |
| 2436 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class SearchFirstStringNode extends Node { private static final int[] UNINTIALIZED_CACHED_INDICES = new int[0]; private final VectorLengthProfile targetLengthProfile = VectorLengthProfile.create(); private final VectorLengthProfile elementsLengthProfile = VectorLengthProfile.create(); private final ValueProfile targetClassProfile = ValueProfile.createClassProfile(); private final ValueProfile elementsClassProfile = ValueProfile.createClassProfile(); @Child private StringEqualsNode stringEquals = CompareStringNode.createEquals(); @Child private CompareStringNode stringStartsWith; @Child private StringEqualsNode equalsDuplicate; private final NACheck elementsNACheck = NACheck.create(); private final NACheck targetNACheck = NACheck.create(); private final BranchProfile everFoundDuplicate = BranchProfile.create(); private final BranchProfile seenInvalid = BranchProfile.create(); /** Instead of using the notFoundStartIndex we use NA. */ private final boolean useNAForNotFound; private final boolean exactMatch; @CompilationFinal(dimensions = 1) private int[] cachedIndices; private SearchFirstStringNode(boolean exactMatch, boolean useNAForNotFound) { this.exactMatch = exactMatch; this.useNAForNotFound = useNAForNotFound; if (!exactMatch) { stringStartsWith = CompareStringNode.createStartsWith(); } } public RAbstractIntVector apply(RAbstractStringVector target, RAbstractStringVector elements, int notFoundStartIndex, RStringVector names) { RAbstractStringVector targetProfiled = targetClassProfile.profile(target); RAbstractStringVector elementsProfiled = elementsClassProfile.profile(elements); int targetLength = targetLengthProfile.profile(targetProfiled.getLength()); int elementsLength = elementsLengthProfile.profile(elementsProfiled.getLength()); targetNACheck.enable(target); elementsNACheck.enable(elements); if (cachedIndices == UNINTIALIZED_CACHED_INDICES) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = searchCached(targetProfiled, targetLength, elementsProfiled, elementsLength, names); } if (cachedIndices != null) { if (!isCacheValid(targetProfiled, targetLength, elementsProfiled, elementsLength, cachedIndices)) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = null; // set to generic // fallthrough to generic } else { assert sameVector(searchCached(target, targetLength, elements, elementsLength, names), cachedIndices); return RDataFactory.createIntVector(cachedIndices, true, names); } } return searchGeneric(targetProfiled, targetLength, elementsProfiled, elementsLength, notFoundStartIndex, false, names); } public static SearchFirstStringNode createNode(boolean exactMatch, boolean useNAForNotFound) { return new SearchFirstStringNode(exactMatch, useNAForNotFound); } private int[] searchCached(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, RStringVector names) { if (exactMatch) { RAbstractIntVector genericResult = searchGeneric(target, targetLength, elements, elementsLength, -1, true, names); if (genericResult != null) { return genericResult.materialize().getReadonlyData(); } } return null; } private boolean isCacheValid(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int[] cached) { int cachedLength = cached.length; if (elementsLength != cachedLength) { seenInvalid.enter(); return false; } for (int i = 0; i < cachedLength; i++) { int cachedIndex = cached[i]; String cachedElement = elements.getDataAt(i); int cachedElementHash = cachedElement.hashCode(); assert !elementsNACheck.check(cachedElement) && cachedElement.length() > 0; int cachedTranslatedIndex = cachedIndex - 1; for (int j = 0; j < cachedTranslatedIndex; j++) { String targetString = target.getDataAt(j); if (!targetNACheck.check(targetString) && stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } if (cachedTranslatedIndex < targetLength) { String targetString = target.getDataAt(cachedTranslatedIndex); if (!targetNACheck.check(targetString) && !stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } else { seenInvalid.enter(); return false; } } return true; } private static boolean sameVector(int[] a, int[] b) { if (a == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } private final BranchProfile notFoundProfile = BranchProfile.create(); private final ConditionProfile hashingProfile = ConditionProfile.createBinaryProfile(); private RAbstractIntVector searchGeneric(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int notFoundStartIndex, boolean nullOnNotFound, RStringVector names) { int[] indices = new int[elementsLength]; boolean resultComplete = true; long hashingCost = targetLength * 10L + 10 /* constant overhead */; long lookupCost = elementsLength * 2L; long nestedLoopCost = targetLength * (long) elementsLength; NonRecursiveHashMapCharacter map; if (hashingProfile.profile(nestedLoopCost > hashingCost + lookupCost)) { map = new NonRecursiveHashMapCharacter(targetLength); for (int i = 0; i < targetLength; i++) { String name = target.getDataAt(i); if (!targetNACheck.check(name)) { map.put(name, i); } } } else { map = null; } int notFoundIndex = notFoundStartIndex; for (int i = 0; i < elementsLength; i++) { String element = elements.getDataAt(i); boolean isElementNA = elementsNACheck.check(element) || element.length() == 0; if (!isElementNA) { int index; if (map != null) { index = map.get(element); if (!exactMatch && index < 0) { // the map is only good for exact matches index = findNonExactIndex(target, targetLength, element); } } else { index = findIndex(target, targetLength, element); } if (index >= 0) { indices[i] = index + 1; continue; } } notFoundProfile.enter(); if (nullOnNotFound) { return null; } else { int prevDuplicateIndex = -1; if (!isElementNA) { prevDuplicateIndex = findFirstDuplicate(elements, element, i); } int nextIndex; if (prevDuplicateIndex == -1) { if (useNAForNotFound) { resultComplete = false; nextIndex = RRuntime.INT_NA; } else { nextIndex = ++notFoundIndex; } } else { nextIndex = indices[prevDuplicateIndex]; } indices[i] = nextIndex; } } return RDataFactory.createIntVector(indices, resultComplete && elements.isComplete(), names); } private int findNonExactIndex(RAbstractStringVector target, int targetLength, String element) { assert !exactMatch; int nonExactIndex = -1; for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { return -1; } } } } return nonExactIndex; } private int findIndex(RAbstractStringVector target, int targetLength, String element) { int nonExactIndex = -1; int elementHash = element.hashCode(); for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringEquals.executeCompare(element, elementHash, targetValue)) { return j; } if (!exactMatch) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { nonExactIndex = -2; } } } } } return nonExactIndex; } private int findFirstDuplicate(RAbstractStringVector elements, String element, int currentIndex) { if (equalsDuplicate == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); equalsDuplicate = insert(CompareStringNode.createEquals()); } int elementHash = element.hashCode(); for (int j = 0; j < currentIndex; j++) { String otherElement = elements.getDataAt(j); if (!targetNACheck.check(otherElement) && equalsDuplicate.executeCompare(element, elementHash, otherElement)) { everFoundDuplicate.enter(); return j; } } return -1; } abstract static class CompareStringNode extends Node { public abstract boolean executeCompare(String a, String b); public static StringEqualsNode createEquals() { return new StringEqualsNode(); } public static StringStartsWithNode createStartsWith() { return new StringStartsWithNode(); } public static class StringEqualsNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); private final ConditionProfile hashEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(a.hashCode() != b.hashCode())) { return false; } return a.equals(b); } } public final boolean executeCompare(String a, int aHash, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(aHash != b.hashCode())) { return false; } return a.equals(b); } } } private static class StringStartsWithNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { return a.startsWith(b); } } } } } |
blob | long method | t | t | f | long method | blob | 0 | 14469 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/SearchFirstStringNode.java/#L46-L361 | 1 | 2436 | 14469 | minor |
| 5309 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14864 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 1 | 5309 | 14864 | minor |
| 1627 | {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11501 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 1627 | 11501 | major |
| 556 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Optional removeUncomparableFieldsFromRecord(Schema record, Set processed) { Preconditions.checkArgument(record.getType() == Schema.Type.RECORD); if (processed.contains(record)) { return Optional.absent(); } processed.add(record); List fields = Lists.newArrayList(); for (Field field : record.getFields()) { Optional newFieldSchema = removeUncomparableFields(field.schema(), processed); if (newFieldSchema.isPresent()) { fields.add(new Field(field.name(), newFieldSchema.get(), field.doc(), field.defaultValue())); } } Schema newSchema = Schema.createRecord(record.getName(), record.getDoc(), record.getNamespace(), false); newSchema.setFields(fields); return Optional.of(newSchema); } |
feature envy | 1: long method | t | t | f | 1: long method | feature envy | 0 | 5609 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java/#L615-L634 | 1 | 556 | 5609 | major |
| 241 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 2643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 241 | 2643 | minor |
| 2394 | YES I found bad smells BAD SMELLS ARE: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14371 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 | 2 | 2394 | 14371 | major |
| 1409 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Long parameter list 5. Shotgun surgery 6. Inappropriate intimacy 7. Unused code 8. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | Long method2 Feature envy3 Duplicate code 4 Long parameter list 5 Shotgun surgery 6 Inappropriate intimacy 7 Unused code 8 Lazy class | t | f | f | . Long method2. Feature envy3. Duplicate code 4. Long parameter list 5. Shotgun surgery 6. Inappropriate intimacy 7. Unused code 8. Lazy class | data class | 0 | 10897 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 2 | 1409 | 10897 | minor |
| 3170 | { "NO, I did not find any bad smell" :"" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | ""} | f | f | f | ""} | blob | 0 | 4457 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 3170 | 4457 | minor |
| 152 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1930 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 152 | 1930 | major |
| 1982 | {"response": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ForeachCommand extends Command { public static String[] foreachArgs = null; public ForeachCommand() { addCommand("foreach", "", "build up a list of elements to operate on "); addCommand("do", "", "repeat a command for each element in the list"); } public void run(String command, final String[] args, final Context context, final PrintStream out) throws DDRInteractiveCommandException { if (command.equals("!do")) { boolean echo = false; boolean quiet = false; String token = null; int commandIndex = 0; while (commandIndex < args.length) { if (args[commandIndex].equals("help")) { out.println("The !do command is used to repeat a command on the elements gathered by the !foreach command."); out.println("Syntax: !do [echo] [quiet] [token=] [args]"); out.println(); out.println("\techo\t\tOutput each command before it is run."); out.println("\tquiet\t\tSuppress delimiters between command outputs."); out.println("\ttoken=\tSpecify a substitution token. Occurrencs of this string in the args will be replaced by the current element."); return; } else if (args[commandIndex].equals("echo")) { echo = true; commandIndex += 1; } else if (args[commandIndex].equals("quiet")) { quiet = true; commandIndex += 1; } else if (args[commandIndex].startsWith("token=")) { token = args[commandIndex].substring("token=".length()); commandIndex += 1; } else { break; } } if (commandIndex >= args.length) { out.println("The do command requires another command to repeat."); return; } if ((null == foreachArgs) || (0 == foreachArgs.length)) { out.println("Element list is empty. Use the foreach command to populate it."); return; } for (int i = 0; i < foreachArgs.length; i++) { if (!quiet && (i > 0)) { out.println("========================================"); } try { String[] newArgs; if (null == token) { newArgs = substituteArgs(args, commandIndex, i); } else { newArgs = substituteArgs(args, commandIndex, i, token); } if (echo) { System.out.println("> " + args[commandIndex] + " " + Arrays.toString(newArgs)); } CommandParser commandParser = new CommandParser(args[commandIndex], newArgs); context.execute(commandParser, out); } catch (ParseException e) { e.printStackTrace(out); } catch (Throwable th) { out.println("Exception while executing " + args[commandIndex] + " " + foreachArgs[i]); th.printStackTrace(out); } } } else if(command.equals("!foreach")) { if (args.length > 0) { out.println("The !foreach command takes no arguments, but will read lines from the console until it encounters a blank line."); out.println("These lines can then be used as arguments to commands specified using !do."); return; } ArrayList lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (0 == line.length()) { break; } else { lines.add(line); } } // split by , String[] newArgs = new String[lines.size()]; lines.toArray(newArgs); foreachArgs = newArgs; } } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex) { /* Concatenate: * */ String[] newArgs = new String[args.length - commandIndex]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); newArgs[newArgs.length - 1] = foreachArgs[foreachIndex]; return newArgs; } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex, String token) { /* Concatenate: * * Replacing any occurence of token with */ String[] newArgs = new String[args.length - commandIndex - 1]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); for (int i = 0; i < newArgs.length; i++) { newArgs[i] = newArgs[i].replace(token, foreachArgs[foreachIndex]); } return newArgs; } } |
blob | long method | t | t | f | long method | blob | 0 | 12643 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/tools/ddrinteractive/commands/ForeachCommand.java/#L37-L165 | 1 | 1982 | 12643 | major |
| 1011 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9271 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1011 | 9271 | minor |
| 2688 | {"message": "YES I found bad smells", "the bad smells are": ["Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | long method | t | t | f | long method | blob | 0 | 15283 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 2688 | 15283 | major |
| 957 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 8546 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 957 | 8546 | major |
| 1723 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11798 | https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 | 1 | 1723 | 11798 | critical |
| 129 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StringFunctions { /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function appendOld(final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function prependOld(final String prefix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterForArrayOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function, String> joinerOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function, String>() { public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function joinerForArrayOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function lengthOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function surroundOld(final String prefix, final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function trimOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toLowerCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toLowerCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toUpperCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toUpperCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function convertCaseOld(final CaseFormat src, final CaseFormat target) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return src.to(target, input); } }; } public static Function append(final String suffix) { return new AppendFunction(checkNotNull(suffix, "suffix")); } private static class AppendFunction implements Function { private final String suffix; public AppendFunction(String suffix) { this.suffix = suffix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; public static Function prepend(final String prefix) { return new PrependFunction(checkNotNull(prefix, "prefix")); } protected static class PrependFunction implements Function { private final String prefix; public PrependFunction(String prefix) { this.prefix = prefix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } } /** given e.g. "hello %s" returns a function which will insert a string into that pattern */ public static Function formatter(final String pattern) { return new FormatterFunction(pattern); } protected static class FormatterFunction implements Function { private final String pattern; FormatterFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object input) { return String.format(pattern, input); } }; /** given e.g. "hello %s %s" returns a function which will insert an array of two strings into that pattern */ public static Function formatterForArray(final String pattern) { return new FormatterForArrayFunction(checkNotNull(pattern, "pattern")); } protected static class FormatterForArrayFunction implements Function { private final String pattern; public FormatterForArrayFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object[] input) { return String.format(pattern, input); } } /** * Given e.g. "hello %s %s" returns a function which will insert an Iterable of two strings into that pattern * * @since 0.9.0 */ public static Function, String> formatterForIterable(final String pattern) { return new FormatterForIterableFunction(pattern); } protected static class FormatterForIterableFunction implements Function, String> { final String pattern; public FormatterForIterableFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Iterable input) { Object[] arr = (input == null) ? null : Iterables.toArray(input, Object.class); return String.format(pattern, arr); } } /** joins the given objects in a collection as a toString with the given separator */ public static Function, String> joiner(final String separator) { return new JoinerFunction(separator); } private static class JoinerFunction implements Function, String> { private final String separator; public JoinerFunction(String separator) { this.separator = separator; } public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } } /** joins the given objects as a toString with the given separator, but expecting an array of objects, not a collection */ public static Function joinerForArray(final String separator) { return new JoinerForArrayFunction(checkNotNull(separator, "separator")); } private static class JoinerForArrayFunction implements Function { private final String separator; protected JoinerForArrayFunction(String separator) { this.separator = separator; } public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } } /** provided here as a convenience; prefer {@link Functions#toStringFunction()} */ public static Function toStringFunction() { return Functions.toStringFunction(); } /** returns function which gives length of input, with -1 for nulls */ public static Function length() { return new LengthFunction(); } protected static class LengthFunction implements Function { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } } /** Surrounds an input string with the given prefix and suffix */ public static Function surround(final String prefix, final String suffix) { Preconditions.checkNotNull(prefix); Preconditions.checkNotNull(suffix); return new SurroundFunction(prefix, suffix); } protected static class SurroundFunction implements Function { private final String prefix; private final String suffix; public SurroundFunction(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } } public static Function trim() { return new TrimFunction(); } protected static class TrimFunction implements Function { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } } public static Function toLowerCase() { return new LowerCaseFunction(); } protected static class LowerCaseFunction implements Function { @Override public String apply(String input) { return input.toLowerCase(); } } public static Function toUpperCase() { return new UpperCaseFunction(); } protected static class UpperCaseFunction implements Function { @Override public String apply(String input) { return input.toUpperCase(); } } public static Function convertCase(final CaseFormat src, final CaseFormat target) { return new ConvertCaseFunction(checkNotNull(src, "src"), checkNotNull(target, "target")); } protected static class ConvertCaseFunction implements Function { private final CaseFormat src; private final CaseFormat target; public ConvertCaseFunction(CaseFormat src, CaseFormat target) { this.src = src; this.target = target; } @Override public String apply(String input) { return src.to(target, input); } } public static class RegexReplacer implements Function { private final String pattern; private final String replacement; public RegexReplacer(String pattern, String replacement) { this.pattern = pattern; this.replacement = replacement; } @Nullable @Override public String apply(@Nullable String s) { return Strings.replaceAllRegex(s, pattern, replacement); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1607 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java/#L32-L415 | 2 | 129 | 1607 | major |
| 1848 | {"output":"YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12186 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 1848 | 12186 | minor |
| 2455 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14522 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 2 | 2455 | 14522 | major |
| 2382 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14339 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 1 | 2382 | 14339 | minor |
| 2329 | YES, I found bad smells the bad smells are: 1. Feature envy: the ExtractTemplateCmd class is heavily reliant on external classes such as CallContext, _templateService, and _responseGenerator, indicating a potential violation of high cohesion. 2. Long method: the execute() method is long and contains multiple levels of indentation, indicating potential complexity and a violation of the Single Responsibility Principle. 3. Duplicate code: the getCommandName() and getStaticName() methods perform the same task, indicating code duplication. 4. Magic numbers: the length value for the url parameter is set to 2048 without any explanation, making it harder for future developers to understand the code. 5. Poor naming: the variable names in some of the parameters (e.g. "url", "zoneId", and "mode") are too generic and lack clarity. 6. Inconsistent formatting: inconsistent spacing and indentation throughout the code can make it difficult to read and maintain. 7. Strong coupling: the ExtractTemplateCmd class is tightly coupled to other classes and methods, making it difficult to change or extend in the future. 8. Incomplete error handling: the execute() method throws a generic ServerApiException without providing any specific error message, making it difficult to troubleshoot issues. 9. Violation of best practices: using underscores in variable names (e.g. "_entityMgr", "_uuidMgr") is not considered a best practice in Java programming. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
blob | Feature envy: the ExtractTemplateCmd class is heavily reliant on external classes such as CallContext, _templateService, and _responseGenerator, indicating a potential violation of high cohesion2 Long method: the execute() method is long and contains multiple levels of indentation, indicating potential complexity and a violation of the Single Responsibility Principle3 Duplicate code: the getCommandName() and getStaticName() methods perform the same task, indicating code duplication4 Magic numbers: the length value for the url parameter is set to 2048 without any explanation, making it harder for future developers to understand the code5 Poor naming: the variable names in some of the parameters (eg "url", "zoneId", and "mode") are too generic and lack clarity6 Inconsistent formatting: inconsistent spacing and indentation throughout the code can make it difficult to read and maintain7 Strong coupling: the ExtractTemplateCmd class is tightly coupled to other classes and methods, making it difficult to change or extend in the future8 Incomplete error handling: the execute() method throws a generic ServerApiException without providing any specific error message, making it difficult to troubleshoot issues9 Violation of best practices: using underscores in variable names (eg "_entityMgr", "_uuidMgr") is not considered a best practice in Java programming | t | f | f | . Feature envy: the ExtractTemplateCmd class is heavily reliant on external classes such as CallContext, _templateService, and _responseGenerator, indicating a potential violation of high cohesion.2. Long method: the execute() method is long and contains multiple levels of indentation, indicating potential complexity and a violation of the Single Responsibility Principle.3. Duplicate code: the getCommandName() and getStaticName() methods perform the same task, indicating code duplication.4. Magic numbers: the length value for the url parameter is set to 2048 without any explanation, making it harder for future developers to understand the code.5. Poor naming: the variable names in some of the parameters (e.g. "url", "zoneId", and "mode") are too generic and lack clarity.6. Inconsistent formatting: inconsistent spacing and indentation throughout the code can make it difficult to read and maintain.7. Strong coupling: the ExtractTemplateCmd class is tightly coupled to other classes and methods, making it difficult to change or extend in the future.8. Incomplete error handling: the execute() method throws a generic ServerApiException without providing any specific error message, making it difficult to troubleshoot issues.9. Violation of best practices: using underscores in variable names (e.g. "_entityMgr", "_uuidMgr") is not considered a best practice in Java programming. | blob | 0 | 14149 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 2 | 2329 | 14149 | minor |
| 1986 | YES I found bad smells The bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Feature envy | t | f | f | .Feature envy | long method | 0 | 12657 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1986 | 12657 | minor |
| 1230 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long methods 3. Getter and setter methods instead of using constructor injection or builder pattern. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy2 Long methods3 Getter and setter methods instead of using constructor injection or builder pattern | t | f | f | . Feature envy2. Long methods3. Getter and setter methods instead of using constructor injection or builder pattern. | data class | 0 | 10362 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 1230 | 10362 | critical |
| 2 | {"YES I found bad smells":"the bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 529 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 2 | 2 | 529 | critical |
| 167 | {"message": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2023 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 2 | 167 | 2023 | major |
| 5390 | { "response": "YES, I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | long method | t | t | f | long method | feature envy | 0 | 15151 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L84931-L84966 | 1 | 5390 | 15151 | minor |
| 2074 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13036 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 2 | 2074 | 13036 | major |
| 3999 | YES I found bad smells the bad smells are: 1. Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks). 2. Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks)2 Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself) | t | f | f | . Long method (the class has only one method, but it could still be considered a long method as it performs multiple tasks).2. Feature envy (the class is accessing a lot of data from other classes instead of handling it within itself). | data class | 0 | 10569 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 2 | 3999 | 10569 | critical |
| 2108 | YES I found bad smells the bad smells are: 1. Feature envy: The getTopLevelIterator method is manipulating data from the topLevelIterators ArrayList, which is outside of its own class. 2. Long method: The constructor contains multiple lines of code, and could be broken down for better organization and readability. 3. Temporary field: The useSample and sampleConf variables are only used in the constructor, but are declared as class fields. 4. Duplicated code: The isFullMajorCompaction and isUserCompaction methods contain almost identical code, violating the DRY principle. 5. Deprecated method: The registerSideChannel method is marked as @Deprecated, indicating that it may be removed in future versions. 6. Inconsistent naming conventions: The class name is inconsistent with other class names in the codebase, using "Offline" instead of "Offline Iterator" like other classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
blob | Feature envy: The getTopLevelIterator method is manipulating data from the topLevelIterators ArrayList, which is outside of its own class2 Long method: The constructor contains multiple lines of code, and could be broken down for better organization and readability3 Temporary field: The useSample and sampleConf variables are only used in the constructor, but are declared as class fields4 Duplicated code: The isFullMajorCompaction and isUserCompaction methods contain almost identical code, violating the DRY principle5 Deprecated method: The registerSideChannel method is marked as @Deprecated, indicating that it may be removed in future versions6 Inconsistent naming conventions: The class name is inconsistent with other class names in the codebase, using "Offline" instead of "Offline Iterator" like other classes | t | f | f | . Feature envy: The getTopLevelIterator method is manipulating data from the topLevelIterators ArrayList, which is outside of its own class.2. Long method: The constructor contains multiple lines of code, and could be broken down for better organization and readability.3. Temporary field: The useSample and sampleConf variables are only used in the constructor, but are declared as class fields.4. Duplicated code: The isFullMajorCompaction and isUserCompaction methods contain almost identical code, violating the DRY principle.5. Deprecated method: The registerSideChannel method is marked as @Deprecated, indicating that it may be removed in future versions.6. Inconsistent naming conventions: The class name is inconsistent with other class names in the codebase, using "Offline" instead of "Offline Iterator" like other classes. | blob | 0 | 13178 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 2 | 2108 | 13178 | minor |
| 3947 | { "output": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | blob | t | t | f | blob | data class | 0 | 10329 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 3947 | 10329 | major |
| 1597 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class StringFunctions { /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function appendOld(final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function prependOld(final String prefix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function formatterForArrayOld(final String pattern) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { return String.format(pattern, input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function, String> joinerOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function, String>() { public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function joinerForArrayOld(final String separator) { // TODO PERSISTENCE WORKAROUND return new Function() { public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function lengthOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function surroundOld(final String prefix, final String suffix) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function trimOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toLowerCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toLowerCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function toUpperCaseOld() { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return input.toUpperCase(); } }; } /** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */ @SuppressWarnings("unused") @Deprecated private static Function convertCaseOld(final CaseFormat src, final CaseFormat target) { // TODO PERSISTENCE WORKAROUND return new Function() { @Override public String apply(String input) { return src.to(target, input); } }; } public static Function append(final String suffix) { return new AppendFunction(checkNotNull(suffix, "suffix")); } private static class AppendFunction implements Function { private final String suffix; public AppendFunction(String suffix) { this.suffix = suffix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return input + suffix; } }; public static Function prepend(final String prefix) { return new PrependFunction(checkNotNull(prefix, "prefix")); } protected static class PrependFunction implements Function { private final String prefix; public PrependFunction(String prefix) { this.prefix = prefix; } @Override @Nullable public String apply(@Nullable String input) { if (input==null) return null; return prefix + input; } } /** given e.g. "hello %s" returns a function which will insert a string into that pattern */ public static Function formatter(final String pattern) { return new FormatterFunction(pattern); } protected static class FormatterFunction implements Function { private final String pattern; FormatterFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object input) { return String.format(pattern, input); } }; /** given e.g. "hello %s %s" returns a function which will insert an array of two strings into that pattern */ public static Function formatterForArray(final String pattern) { return new FormatterForArrayFunction(checkNotNull(pattern, "pattern")); } protected static class FormatterForArrayFunction implements Function { private final String pattern; public FormatterForArrayFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Object[] input) { return String.format(pattern, input); } } /** * Given e.g. "hello %s %s" returns a function which will insert an Iterable of two strings into that pattern * * @since 0.9.0 */ public static Function, String> formatterForIterable(final String pattern) { return new FormatterForIterableFunction(pattern); } protected static class FormatterForIterableFunction implements Function, String> { final String pattern; public FormatterForIterableFunction(String pattern) { this.pattern = pattern; } public String apply(@Nullable Iterable input) { Object[] arr = (input == null) ? null : Iterables.toArray(input, Object.class); return String.format(pattern, arr); } } /** joins the given objects in a collection as a toString with the given separator */ public static Function, String> joiner(final String separator) { return new JoinerFunction(separator); } private static class JoinerFunction implements Function, String> { private final String separator; public JoinerFunction(String separator) { this.separator = separator; } public String apply(@Nullable Iterable input) { return Strings.join(input, separator); } } /** joins the given objects as a toString with the given separator, but expecting an array of objects, not a collection */ public static Function joinerForArray(final String separator) { return new JoinerForArrayFunction(checkNotNull(separator, "separator")); } private static class JoinerForArrayFunction implements Function { private final String separator; protected JoinerForArrayFunction(String separator) { this.separator = separator; } public String apply(@Nullable Object[] input) { if (input == null) return Strings.EMPTY; return Strings.join(input, separator); } } /** provided here as a convenience; prefer {@link Functions#toStringFunction()} */ public static Function toStringFunction() { return Functions.toStringFunction(); } /** returns function which gives length of input, with -1 for nulls */ public static Function length() { return new LengthFunction(); } protected static class LengthFunction implements Function { @Override public Integer apply(@Nullable String input) { if (input == null) return -1; return input.length(); } } /** Surrounds an input string with the given prefix and suffix */ public static Function surround(final String prefix, final String suffix) { Preconditions.checkNotNull(prefix); Preconditions.checkNotNull(suffix); return new SurroundFunction(prefix, suffix); } protected static class SurroundFunction implements Function { private final String prefix; private final String suffix; public SurroundFunction(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } @Override public String apply(@Nullable String input) { if (input == null) return null; return prefix+input+suffix; } } public static Function trim() { return new TrimFunction(); } protected static class TrimFunction implements Function { @Override public String apply(@Nullable String input) { if (input == null) return null; if (Strings.isBlank(input)) return Strings.EMPTY; return CharMatcher.BREAKING_WHITESPACE.trimFrom(input); } } public static Function toLowerCase() { return new LowerCaseFunction(); } protected static class LowerCaseFunction implements Function { @Override public String apply(String input) { return input.toLowerCase(); } } public static Function toUpperCase() { return new UpperCaseFunction(); } protected static class UpperCaseFunction implements Function { @Override public String apply(String input) { return input.toUpperCase(); } } public static Function convertCase(final CaseFormat src, final CaseFormat target) { return new ConvertCaseFunction(checkNotNull(src, "src"), checkNotNull(target, "target")); } protected static class ConvertCaseFunction implements Function { private final CaseFormat src; private final CaseFormat target; public ConvertCaseFunction(CaseFormat src, CaseFormat target) { this.src = src; this.target = target; } @Override public String apply(String input) { return src.to(target, input); } } public static class RegexReplacer implements Function { private final String pattern; private final String replacement; public RegexReplacer(String pattern, String replacement) { this.pattern = pattern; this.replacement = replacement; } @Nullable @Override public String apply(@Nullable String s) { return Strings.replaceAllRegex(s, pattern, replacement); } } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 11414 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java/#L32-L415 | 1 | 1597 | 11414 | major |
| 1849 | {"response": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 12187 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 2 | 1849 | 12187 | major |
| 17 | { "result": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DimsDataList implements Serializable { /** * */ private static final long serialVersionUID = -5902704017223885965L; private List dimsData; private boolean expression; public DimsDataList() { } public DimsDataList(List chunk) { dimsData = chunk; } public DimsDataList(int[] dataShape) throws Exception { try { // For now we just assume the first dimensions are the slow ones to make an axis out // of. Later read the axis from the meta list but we do not have examples of this so // far. int xaxis=-1,yaxis=-1; for (int i = 0; i=0; i--) { if (dataShape[i]>1) { if (yaxis<0) { getDimsData(i).setPlotAxis(AxisType.Y); yaxis = i; continue; } else if (xaxis<0) { getDimsData(i).setPlotAxis(AxisType.X); xaxis = i; continue; } } } // If we only found a y it may be a multiple-dimension set with only 1D possible. // In that case change y to x. if (yaxis>-1 && xaxis<0) { getDimsData(yaxis).setPlotAxis(AxisType.X); } } finally { //file.close(); } } public Iterable iterable() { return dimsData; } public void add(DimsData dimension) { if (dimsData==null) dimsData = new ArrayList(3); if (dimsData.size()>dimension.getDimension() && dimension.getDimension()>-1) { dimsData.set(dimension.getDimension(), dimension); } else { dimsData.add(dimension); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dimsData == null) ? 0 : dimsData.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DimsDataList other = (DimsDataList) obj; if (dimsData == null) { if (other.dimsData != null) return false; } else if (!dimsData.equals(other.dimsData)) return false; return true; } public static Object[] getDefault() { return new DimsData[]{new DimsData(0)}; } public Object[] getElements() { if (dimsData==null) return null; return dimsData.toArray(new DimsData[dimsData.size()]); } public int size() { if (dimsData==null) return 0; return dimsData.size(); } public DimsData getDimsData(int i) { if (dimsData==null) return null; return dimsData.get(i); } public Iterator iterator() { if (dimsData==null) return null; return dimsData.iterator(); } public void clear() { if (dimsData!=null) dimsData.clear(); } public String toString() { return toString(null); } public String toString(int[] shape) { final StringBuilder buf = new StringBuilder(); buf.append("[ "); int index = 0; for (DimsData d : dimsData) { final int upper = shape!=null ? shape[index] : -1; buf.append(d.getUserString(upper)); if (d!=dimsData.get(dimsData.size()-1)) buf.append(", "); ++index; } buf.append(" ]"); return buf.toString(); } public boolean isRangeDefined() { for (DimsData data : iterable()) { if (data.getSliceRange()!=null) return true; } return false; } public int getAxisCount() { if (dimsData==null) return -1; int count = 0; for (DimsData dd : dimsData) { if (!dd.getPlotAxis().hasValue()) count++; } return count; } public int getRangeCount() { int count = 0; for (DimsData dd : dimsData) { if (dd.getPlotAxis()==AxisType.RANGE) count++; } return count; } public boolean is2D() { return getAxisCount()==2; } public DimsDataList clone() { final DimsDataList clone = new DimsDataList(); for (DimsData dd : iterable()) { DimsData dnew = dd.clone(); clone.add(dnew); } clone.expression = expression; return clone; } /** * Sets any axes there are to the axis passed in */ public void normalise(AxisType axis) { for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) dd.setPlotAxis(axis); } } /** * Probably not best algorithm but we are dealing with very small arrays here. * This is simply trying to ensure that only one dimension is selected as an * axis because the plot has changed. * * @param iaxisToFind */ public void setSingleAxisOnly(AxisType iaxisToFind, AxisType iaxisValue) { DimsData found = null; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==iaxisToFind) { dd.setPlotAxis(iaxisValue); found=dd; } } if (found!=null) { for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is x for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) { dd.setPlotAxis(iaxisValue); found=dd; } } for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis */ public void setTwoAxesOnly(AxisType firstAxis, AxisType secondAxis) { boolean foundFirst = false, foundSecond = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; } if (foundFirst&&foundSecond) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis * @param thirdAxis */ public void setThreeAxesOnly(AxisType firstAxis, AxisType secondAxis, AxisType thirdAxis) { boolean foundFirst = false, foundSecond = false, foundThird = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; if (dd.getPlotAxis()==thirdAxis) foundThird = true; } if (foundFirst&&foundSecond&&foundThird) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis, thirdAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis, thirdAxis); if (!foundThird) foundThird = processAxis(thirdAxis, firstAxis, secondAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } private final boolean processAxis(AxisType axis, AxisType... ignoredAxes) { final List ignored = asList(ignoredAxes); for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue() && !ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } for (DimsData dd : iterable()) { if (!ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } return false; } /** * Convert a primitive array to a list. * @param array - an array of primitives * @return */ @SuppressWarnings("unchecked") private static final List asList(final Object array) { if (!array.getClass().isArray()) throw new IllegalArgumentException("Not an array"); return new AbstractList() { @Override public T get(int index) { return (T) Array.get(array, index); } @Override public int size() { return Array.getLength(array); } }; } public boolean isXFirst() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().hasValue()) continue; return dd.getPlotAxis()==AxisType.X; } return false; } public void reverseImage() { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==AxisType.X) { dd.setPlotAxis(AxisType.Y); continue; } if (dd.getPlotAxis()==AxisType.Y) { dd.setPlotAxis(AxisType.X); continue; } } } public boolean isExpression() { return expression; } public void setExpression(boolean expression) { this.expression = expression; } public boolean isEmpty() { return dimsData==null || dimsData.isEmpty(); } public boolean isAdvanced() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().isAdvanced()) return true; } return false; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public List getDimsData() { return dimsData; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public void setDimsData(List dimsData) { this.dimsData = dimsData; } public void removeLargeStacks(ISliceSystem slicingSystem, int maxStack) { for (DimsData dd : getDimsData()) { if (dd.getPlotAxis().isStack(slicingSystem)) { if (dd.getSliceRange(true)==null || "".equals(dd.getSliceRange(true)) || "all".equals(dd.getSliceRange(true))) { final ILazyDataset lz = slicingSystem.getData().getLazySet(); if (lz!=null) { final int size = lz.getShape()[dd.getDimension()]; if (size>=maxStack) { // We set a default slice dd.setSliceRange("0:25"); } } } } } } public Slice[] toSliceArray(int[] dataShape) { final Slice[] ret = new Slice[size()]; for (int i = 0; i < size(); i++) { DimsData dd = getDimsData(i); if (dd.isSlice()) { ret[i] = new Slice(dd.getSlice(), dd.getSlice()+1); } else { ret[i] = new Slice(dataShape[dd.getDimension()]); } } return ret; } /** * Export to Map from DimsDataList * @return */ public Map toMap() { final Map ret = new HashMap(size()); for (DimsData dd : iterable()) { if (dd.isSlice()) { ret.put(dd.getDimension(), String.valueOf(dd.getSlice())); } else if (dd.isTextRange()) { ret.put(dd.getDimension(), dd.getSliceRange()!=null ? dd.getSliceRange() : "all"); } else if ( dd.getPlotAxis()!=null){ ret.put(dd.getDimension(), dd.getPlotAxis().getName()); } } return ret; } /** * Set the current DimsDataList to what is defined in the pass in map. * @param map * @param shape */ public void fromMap(Map map, int[] shape) { clear(); for (int i = 0; i < shape.length; i++) { add(new DimsData(i)); } if (map.isEmpty()) { // Make one up getDimsData(0).setSliceRange("all"); if (size()==2) { getDimsData(1).setPlotAxis(AxisType.X); } else if (size()>2) { getDimsData(1).setPlotAxis(AxisType.Y); getDimsData(2).setPlotAxis(AxisType.X); for (int i = 3; i < size(); i++) { getDimsData(i).setSlice(0); } } } else { // Init one from map saved int dim = 0; for (DimsData dd : iterable()) { String value = map.get(dd.getDimension()); if (value==null) value = map.get(String.valueOf(dd.getDimension())); if (value!=null) { if ("all".equals(value)) { dd.setPlotAxis(AxisType.RANGE); continue; } AxisType at = AxisType.forLabel(value); if (at!=null) { dd.setPlotAxis(at); continue; } try { dd.setSlice(Integer.parseInt(value)); } catch (Exception ne) { dd.setSliceRange(value); } } else { AxisType type = AxisType.forAxis(dim); dd.setPlotAxis(type); ++dim; } } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 652 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.slicing.api/src/org/eclipse/dawnsci/slicing/api/system/DimsDataList.java/#L26-L549 | 1 | 17 | 652 | critical |
| 1341 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 10742 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 2 | 1341 | 10742 | major |
| 2386 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14349 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 | 2 | 2386 | 14349 | minor |
| 2702 | {"response": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 15334 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 2702 | 15334 | major |
| 2354 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | long method | t | t | f | long method | data class | 0 | 14226 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 1 | 2354 | 14226 | major |
| 4481 | {"message": "YES I found bad smells", "the bad smells are": ["Long Method", "Long Method", "Long Method", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | long method, long method, long method, long method | t | t | f | long method, long method, long method, long method | blob | 0 | 11863 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 1 | 4481 | 11863 | critical |
| 222 | {"answer":"YES I found bad smells","bad smells":["1. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DynamicWebAppClusterImpl extends DynamicClusterImpl implements DynamicWebAppCluster { private static final Logger log = LoggerFactory.getLogger(DynamicWebAppClusterImpl.class); private static final FilenameToWebContextMapper FILENAME_TO_WEB_CONTEXT_MAPPER = new FilenameToWebContextMapper(); /** * Instantiate a new DynamicWebAppCluster. Parameters as per {@link DynamicCluster#DynamicCluster()} */ public DynamicWebAppClusterImpl() { super(); } @Override public void init() { super.init(); // Enricher attribute setup. A way of automatically discovering these (but avoiding // averaging things like HTTP port and response codes) would be neat. List>> summingEnricherSetup = ImmutableList.of( ImmutableList.of(REQUEST_COUNT, REQUEST_COUNT), ImmutableList.of(ERROR_COUNT, ERROR_COUNT), ImmutableList.of(REQUESTS_PER_SECOND_LAST, REQUESTS_PER_SECOND_LAST), ImmutableList.of(REQUESTS_PER_SECOND_IN_WINDOW, REQUESTS_PER_SECOND_IN_WINDOW), ImmutableList.of(TOTAL_PROCESSING_TIME, TOTAL_PROCESSING_TIME), ImmutableList.of(PROCESSING_TIME_FRACTION_IN_WINDOW, PROCESSING_TIME_FRACTION_IN_WINDOW) ); List>> averagingEnricherSetup = ImmutableList.of( ImmutableList.of(REQUEST_COUNT, REQUEST_COUNT_PER_NODE), ImmutableList.of(ERROR_COUNT, ERROR_COUNT_PER_NODE), ImmutableList.of(REQUESTS_PER_SECOND_LAST, REQUESTS_PER_SECOND_LAST_PER_NODE), ImmutableList.of(REQUESTS_PER_SECOND_IN_WINDOW, REQUESTS_PER_SECOND_IN_WINDOW_PER_NODE), ImmutableList.of(TOTAL_PROCESSING_TIME, TOTAL_PROCESSING_TIME_PER_NODE), ImmutableList.of(PROCESSING_TIME_FRACTION_IN_WINDOW, PROCESSING_TIME_FRACTION_IN_WINDOW_PER_NODE) ); for (List> es : summingEnricherSetup) { AttributeSensor t = es.get(0); AttributeSensor total = es.get(1); enrichers().add(Enrichers.builder() .aggregating(t) .publishing(total) .fromMembers() .computingSum() .build()); } for (List> es : averagingEnricherSetup) { @SuppressWarnings("unchecked") AttributeSensor t = (AttributeSensor) es.get(0); @SuppressWarnings("unchecked") AttributeSensor average = (AttributeSensor) es.get(1); enrichers().add(Enrichers.builder() .aggregating(t) .publishing(average) .fromMembers() .computingAverage() .defaultValueForUnreportedSensors(0) .build()); } } // TODO this will probably be useful elsewhere ... but where to put it? // TODO add support for this in DependentConfiguration (see TODO there) /** Waits for the given target to report service up, then runs the given task * (often an invocation on that entity), with the given name. * If the target goes away, this task marks itself inessential * before failing so as not to cause a parent task to fail. */ static Task whenServiceUp(final Entity target, final TaskAdaptable task, String name) { return Tasks.builder().displayName(name).dynamic(true).body(new Callable() { @Override public T call() { try { while (true) { if (!Entities.isManaged(target)) { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed"); } if (Boolean.TRUE.equals(target.getAttribute(Attributes.SERVICE_UP))) { Tasks.resetBlockingDetails(); TaskTags.markInessential(task); DynamicTasks.queue(task); try { return task.asTask().getUnchecked(); } catch (Exception e) { if (Entities.isManaged(target)) { throw Exceptions.propagate(e); } else { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed", e); } } } else { Tasks.setBlockingDetails("Waiting on "+target+" to be ready"); } // TODO replace with subscription? Time.sleep(Duration.ONE_SECOND); } } finally { Tasks.resetBlockingDetails(); } } }).build(); } @Override public void deploy(String url, String targetName) { checkNotNull(url, "url"); checkNotNull(targetName, "targetName"); targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // set it up so future nodes get the right wars addToWarsByContext(this, url, targetName); log.debug("Deploying "+targetName+"->"+url+" across cluster "+this+"; WARs now "+getConfig(WARS_BY_CONTEXT)); Iterable targets = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName("Deploy "+targetName+" to cluster (size "+Iterables.size(targets)+")"); for (Entity target: targets) { tb.add(whenServiceUp(target, Effectors.invocation(target, DEPLOY, MutableMap.of("url", url, "targetName", targetName)), "Deploy "+targetName+" to "+target+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); // Update attribute // TODO support for atomic sensor update (should be part of standard tooling; NB there is some work towards this, according to @aledsage) Set deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS)); deployedWars.add(targetName); sensors().set(DEPLOYED_WARS, deployedWars); } @Override public void undeploy(String targetName) { checkNotNull(targetName, "targetName"); targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // set it up so future nodes get the right wars if (!removeFromWarsByContext(this, targetName)) { DynamicTasks.submit(Tasks.warning("Context "+targetName+" not known at "+this+"; attempting to undeploy regardless", null), this); } log.debug("Undeploying "+targetName+" across cluster "+this+"; WARs now "+getConfig(WARS_BY_CONTEXT)); Iterable targets = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName("Undeploy "+targetName+" across cluster (size "+Iterables.size(targets)+")"); for (Entity target: targets) { tb.add(whenServiceUp(target, Effectors.invocation(target, UNDEPLOY, MutableMap.of("targetName", targetName)), "Undeploy "+targetName+" at "+target+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); // Update attribute Set deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS)); deployedWars.remove( FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName) ); sensors().set(DEPLOYED_WARS, deployedWars); } static void addToWarsByContext(Entity entity, String url, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // TODO a better way to do atomic updates, see comment above synchronized (entity) { Map newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); newWarsMap.put(targetName, url); entity.config().set(WARS_BY_CONTEXT, newWarsMap); } } static boolean removeFromWarsByContext(Entity entity, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // TODO a better way to do atomic updates, see comment above synchronized (entity) { Map newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); String url = newWarsMap.remove(targetName); if (url==null) { return false; } entity.config().set(WARS_BY_CONTEXT, newWarsMap); return true; } } @Override public void redeployAll() { Map wars = MutableMap.copyOf(getConfig(WARS_BY_CONTEXT)); String redeployPrefix = "Redeploy all WARs (count "+wars.size()+")"; log.debug("Redeplying all WARs across cluster "+this+": "+getConfig(WARS_BY_CONTEXT)); Iterable targetEntities = Iterables.filter(getChildren(), CanDeployAndUndeploy.class); TaskBuilder tb = Tasks.builder().parallel(true).displayName(redeployPrefix+" across cluster (size "+Iterables.size(targetEntities)+")"); for (Entity targetEntity: targetEntities) { TaskBuilder redeployAllToTarget = Tasks.builder().displayName(redeployPrefix+" at "+targetEntity+" (after ready check)"); for (String warContextPath: wars.keySet()) { redeployAllToTarget.add(Effectors.invocation(targetEntity, DEPLOY, MutableMap.of("url", wars.get(warContextPath), "targetName", warContextPath))); } tb.add(whenServiceUp(targetEntity, redeployAllToTarget.build(), redeployPrefix+" at "+targetEntity+" when ready")); } DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked(); } } |
blob | 1. feature envy | t | t | f | 1. feature envy | blob | 0 | 2413 | https://github.com/apache/brooklyn-library/blob/89795c5d67d594259df9b4ea8bae766660e8b283/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterImpl.java/#L62-L261 | 1 | 222 | 2413 | major |
| 1749 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | f | f | f | data class | 0 | 11857 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 2 | 1749 | 11857 | critical | ||
| 676 | YES I found bad smells the bad smells are: 1. Duplicate code (the definition of schema and value variables are repeated) 2. Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes) 3. Lazy class (the class only contains basic getters and setters) 4. Long method (the toString method is long and contains multiple statements) 5. Magic number (the value null is assigned to the NULL variable without explanation) 6. Indecent exposure (the schema and value variables are defined as public) 7. Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | Duplicate code (the definition of schema and value variables are repeated)2 Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes)3 Lazy class (the class only contains basic getters and setters)4 Long method (the toString method is long and contains multiple statements)5 Magic number (the value null is assigned to the NULL variable without explanation)6 Indecent exposure (the schema and value variables are defined as public)7 Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | t | f | f | . Duplicate code (the definition of schema and value variables are repeated)2. Feature envy (the equals method is using attributes from the SchemaAndValue class instead of its own attributes)3. Lazy class (the class only contains basic getters and setters)4. Long method (the toString method is long and contains multiple statements)5. Magic number (the value null is assigned to the NULL variable without explanation)6. Indecent exposure (the schema and value variables are defined as public)7. Unnecessary variables (the schema and value variables could be defined directly in the constructor instead of using a temporary variable) | data class | 0 | 6576 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 2 | 676 | 6576 | minor |
| 1638 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11532 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 1 | 1638 | 11532 | major | ||
| 570 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. No consistent naming convention used for method names 4. Unused method parameters (e.g. accountId, dataCenterId) 5. Inconsistent parameter ordering in methods 6. Methods with multiple responsibilities (e.g. findVMByHostNameInZone and findVMByInstanceName) 7. Unclear comments or lack of comments 8. Inconsistent formatting and use of whitespace 9. Lack of encapsulation in interface (e.g. public access modifier for methods) 10. Potential code duplication (e.g. listByHostAndState and listByHostIdTypes performing similar tasks) 11. Use of raw types instead of generics (e.g. Pair, Map instead of Pair<T1, T2>, Map<K, V>) 12. Confusing or unclear method names (e.g. listNonExpungedByTemplate) 13. Lack of exception handling or error checking in some methods 14. Possible dead code (e.g. listStartingWithNoHostId has no implementation) 15. Possible performance issues with nested data structures (e.g. Pair, Map> which could cause high memory usage) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); } |
blob | Long method2 Feature envy3 No consistent naming convention used for method names4 Unused method parameters (eg accountId, dataCenterId)5 Inconsistent parameter ordering in methods6 Methods with multiple responsibilities (eg findVMByHostNameInZone and findVMByInstanceName)7 Unclear comments or lack of comments8 Inconsistent formatting and use of whitespace9 Lack of encapsulation in interface (eg public access modifier for methods) | t | f | f | . Long method2. Feature envy3. No consistent naming convention used for method names4. Unused method parameters (e.g. accountId, dataCenterId)5. Inconsistent parameter ordering in methods6. Methods with multiple responsibilities (e.g. findVMByHostNameInZone and findVMByInstanceName)7. Unclear comments or lack of comments8. Inconsistent formatting and use of whitespace9. Lack of encapsulation in interface (e.g. public access modifier for methods) | blob | 0 | 5736 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 | 2 | 570 | 5736 | minor |
| 299 | YES I found bad smells: -The method name is not descriptive. -The parameter names are not descriptive. -There is no logic or explanation for the code. -The code is not properly formatted or indented. The bad smells are: 1. Poorly named method 2. Poorly named parameters 3. Lack of logic/explanation 4. Poor formatting/indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | Poorly named method2 Poorly named parameters3 Lack of logic/explanation4 Poor formatting/indentation | t | f | f | . Poorly named method2. Poorly named parameters3. Lack of logic/explanation4. Poor formatting/indentation | feature envy | 0 | 3147 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 2 | 299 | 3147 | minor |
| 1581 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | t | f | f | data class | 0 | 11362 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 1581 | 11362 | critical | ||
| 440 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: interface Failover { String PREFIX = HdfsClientConfigKeys.PREFIX + "failover."; String PROXY_PROVIDER_KEY_PREFIX = PREFIX + "proxy.provider"; String MAX_ATTEMPTS_KEY = PREFIX + "max.attempts"; int MAX_ATTEMPTS_DEFAULT = 15; String SLEEPTIME_BASE_KEY = PREFIX + "sleep.base.millis"; int SLEEPTIME_BASE_DEFAULT = 500; String SLEEPTIME_MAX_KEY = PREFIX + "sleep.max.millis"; int SLEEPTIME_MAX_DEFAULT = 15000; String CONNECTION_RETRIES_KEY = PREFIX + "connection.retries"; int CONNECTION_RETRIES_DEFAULT = 0; String CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = PREFIX + "connection.retries.on.timeouts"; int CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; String RANDOM_ORDER = PREFIX + "random.order"; boolean RANDOM_ORDER_DEFAULT = false; String RESOLVE_ADDRESS_NEEDED_KEY = PREFIX + "resolve-needed"; boolean RESOLVE_ADDRESS_NEEDED_DEFAULT = false; String RESOLVE_SERVICE_KEY = PREFIX + "resolver.impl"; } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4300 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java/#L274-L294 | 2 | 440 | 4300 | major |
| 2150 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | "YES I found bad smells", "detected_bad_smells" | t | f | f | "YES I found bad smells", "detected_bad_smells" | data class | 0 | 13287 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 2150 | 13287 | minor |
| 3883 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
blob | data class | t | t | f | data class | blob | 0 | 10140 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 3883 | 10140 | minor |
| 364 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Switch statements 3. Long method 4. Feature envy 5. String concatenation in conditional statement 6. Using if/else statements instead of polymorphism | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ContentVisitor implements IContentVisitor { public Object visit( IContent content, Object value ) { return visitContent( content, value ); } public Object visitContent( IContent content, Object value ) { boolean isInline = PropertyUtil.isInlineElement( content ); if ( isInline ) { return new InlineBlockLayout( context, parent, content ); } else { return new BlockStackingLayout( context, parent, content); } } public Object visitPage( IPageContent page, Object value ) { return new PageLayout(executor, context, parent, page); } public Object visitContainer( IContainerContent container, Object value ) { boolean isInline = PropertyUtil.isInlineElement( container ); if ( isInline ) { return new InlineContainerLayout( context, parent, container); } else { return new BlockStackingLayout( context, parent, container); } } public Object visitTable( ITableContent table, Object value ) { return new TableLayout( context, parent, table ); } public Object visitTableBand( ITableBandContent tableBand, Object value ) { return new TableBandLayout( context, parent, tableBand); } public Object visitRow( IRowContent row, Object value ) { return new RowLayout( context, parent, row ); } public Object visitCell( ICellContent cell, Object value ) { return new CellLayout( context, parent, cell ); } public Object visitText( ITextContent text, Object value ) { // FIXME return handleText( text ); } public Object visitLabel( ILabelContent label, Object value ) { return handleText( label ); } public Object visitData( IDataContent data, Object value ) { return handleText( data ); } public Object visitImage( IImageContent image, Object value ) { return new ImageLayout( context, parent, image ); } public Object visitForeign( IForeignContent foreign, Object value ) { boolean isInline = PropertyUtil.isInlineElement( foreign ); if ( isInline ) { return new InlineContainerLayout( context, parent, foreign); } else { return new BlockStackingLayout( context, parent, foreign); } } public Object visitAutoText( IAutoTextContent autoText, Object value ) { int type = autoText.getType( ); if ( type == IAutoTextContent.TOTAL_PAGE || type == IAutoTextContent.UNFILTERED_TOTAL_PAGE ) { context.addUnresolvedContent( autoText ); return new TemplateLayout( context, parent, autoText ); } return handleText( autoText ); } private Object handleText( ITextContent content ) { boolean isInline = parent instanceof IInlineStackingLayout; if ( isInline ) { return new InlineTextLayout( context, parent, content ); } else { String text = content.getText( ); if ( text == null || "".equals( text ) ) //$NON-NLS-1$ { content.setText( " " ); //$NON-NLS-1$ } return new BlockTextLayout( context, parent, content); } } public Object visitList( IListContent list, Object value ) { return new ListLayout( context, parent, list ); } public Object visitListBand( IListBandContent listBand, Object value ) { assert ( false ); return null; // return new PDFListBandLM(context, parent, listBand, emitter, // executor); } public Object visitListGroup( IListGroupContent group, Object value ) { return new ListGroupLayout( context, parent, group ); } public Object visitTableGroup( ITableGroupContent group, Object value ) { return new TableGroupLayout( context, parent, group ); } public Object visitGroup( IGroupContent group, Object value ) { return new BlockStackingLayout( context, parent, group ); } } |
blob | Duplicate code2 Switch statements3 Long method4 Feature envy5 String concatenation in conditional statement6 Using if/else statements instead of polymorphism | t | f | f | . Duplicate code2. Switch statements3. Long method4. Feature envy5. String concatenation in conditional statement6. Using if/else statements instead of polymorphism | blob | 0 | 3715 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/emitter/LayoutContextFactory.java/#L73-L226 | 2 | 364 | 3715 | minor |
| 725 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
blob | data class | t | t | f | data class | blob | 0 | 6841 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 1 | 725 | 6841 | minor |
| 1949 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
blob | f | f | f | blob | 0 | 12529 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 2 | 1949 | 12529 | major | ||
| 3535 | {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JcloudsBlobStoreBasedObjectStore implements PersistenceObjectStore { private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStore.class); private final String containerNameFirstPart; private final String containerSubPath; private String locationSpec; private JcloudsLocation location; private BlobStoreContext context; private ManagementContext mgmt; public JcloudsBlobStoreBasedObjectStore(String locationSpec, String containerName) { this.locationSpec = locationSpec; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; } private String[] splitOnce(String path) { String separator = subPathSeparator(); int index = path.indexOf(separator); if (index<0) return new String[] { path, "" }; return new String[] { path.substring(0, index), path.substring(index+separator.length()) }; } public JcloudsBlobStoreBasedObjectStore(JcloudsLocation location, String containerName) { this.location = location; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; getBlobStoreContext(); } public String getSummaryName() { return (locationSpec!=null ? locationSpec : location)+":"+getContainerNameFull(); } public synchronized BlobStoreContext getBlobStoreContext() { if (context==null) { if (location==null) { Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null"); Preconditions.checkNotNull(mgmt, "mgmt not injected / object store not prepared"); location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec); } String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null"); String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null"); String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null"); String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT); context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential); // TODO do we need to get location from region? can't see the jclouds API. // doesn't matter in some places because it's already in the endpoint // String region = location.getConfig(CloudLocationConfig.CLOUD_REGION_ID); context.getBlobStore().createContainerInLocation(null, getContainerNameFirstPart()); } return context; } @Override public void prepareForMasterUse() { // backups not supported here, that is all which is needed for master use // that's now normally done *prior* to calling in to here for writes // (and we have already thrown in prepareForSharedUse if legacy backups have been specified as required) } public String getContainerName() { return getContainerNameFull(); } protected String getContainerNameFull() { return mergePaths(containerNameFirstPart, containerSubPath); } protected String getContainerNameFirstPart() { return containerNameFirstPart; } protected String getItemInContainerSubPath(String path) { if (Strings.isBlank(containerSubPath)) return path; return mergePaths(containerSubPath, path); } @Override public void createSubPath(String subPath) { // not needed - subpaths are created on demant // (and buggy on softlayer w swift w jclouds 1.7.2: // throws a "not found" if we're creating an empty directory from scratch) // context.getBlobStore().createDirectory(getContainerName(), subPath); } protected void checkPrepared() { if (context==null) throw new IllegalStateException("object store not prepared"); } @Override public StoreObjectAccessor newAccessor(String path) { checkPrepared(); return new JcloudsStoreObjectAccessor(context.getBlobStore(), getContainerNameFirstPart(), getItemInContainerSubPath(path)); } protected String mergePaths(String basePath, String ...subPaths) { StringBuilder result = new StringBuilder(basePath); for (String subPath: subPaths) { if (result.length()>0 && subPath.length()>0) { result.append(subPathSeparator()); result.append(subPath); } } return result.toString(); } protected String subPathSeparator() { // in case some object stores don't allow / for paths return "/"; } @Override public List listContentsWithSubPath(final String parentSubPath) { checkPrepared(); return FluentIterable.from(context.getBlobStore().list(getContainerNameFirstPart(), ListContainerOptions.Builder.inDirectory(getItemInContainerSubPath(parentSubPath)))) .transform(new Function() { @Override public String apply(@javax.annotation.Nullable StorageMetadata input) { String result = input.getName(); result = Strings.removeFromStart(result, containerSubPath); result = Strings.removeFromStart(result, "/"); return result; } }).toList(); } @Override public void close() { if (context!=null) context.close(); } @Override public String toString() { return Objects.toStringHelper(this) .add("blobStoreContext", context) .add("basedir", containerNameFirstPart) .toString(); } @Override public void injectManagementContext(ManagementContext mgmt) { if (this.mgmt!=null && !this.mgmt.equals(mgmt)) throw new IllegalStateException("Cannot change mgmt context of "+this); this.mgmt = mgmt; } @SuppressWarnings("deprecation") @Override public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) { if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this); getBlobStoreContext(); if (persistMode==null || persistMode==PersistMode.DISABLED) { log.warn("Should not be using "+this+" when persistMode is "+persistMode); return; } Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED); if (Boolean.TRUE.equals(backups)) { log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location."); throw new FatalConfigurationRuntimeException("Backups not supported for object store ("+this+")"); } } @Override public void deleteCompletely() { if (Strings.isBlank(containerSubPath)) getBlobStoreContext().getBlobStore().deleteContainer(containerNameFirstPart); else newAccessor(containerSubPath).delete(); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 7670 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java/#L52-L237 | 1 | 3535 | 7670 | minor |
| 2370 | YES I found bad smells. The bad smells are: Long method, Feature envy, Duplicate code, Long parameter list, Comments, Excessive indentation, Shotgun surgery, Primitive obsession, Lazy class, Data clumps, Repetitive code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } } |
blob | Long method, Feature envy, Duplicate code, Long parameter list, Comments, Excessive indentation, Shotgun surgery, Primitive obsession, Lazy class, Data clumps, Repetitive code | t | f | f | Long method, Feature envy, Duplicate code, Long parameter list, Comments, Excessive indentation, Shotgun surgery, Primitive obsession, Lazy class, Data clumps, Repetitive code. | blob | 0 | 14305 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 | 2 | 2370 | 14305 | minor |
| 1964 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12590 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 1964 | 12590 | minor |
| 1540 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic number (8) 4. Nested conditionals (if/else) 5. Use of null (Objects.requireNonNull) 6. Use of unchecked annotations (@SuppressWarnings) 7. Use of volatile variables 8. Use of AtomicReferenceFieldUpdater 9. Lack of consistent formatting and naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class MonoWhen extends Mono implements SourceProducer { final boolean delayError; final Publisher[] sources; final Iterable> sourcesIterable; MonoWhen(boolean delayError, Publisher... sources) { this.delayError = delayError; this.sources = Objects.requireNonNull(sources, "sources"); this.sourcesIterable = null; } MonoWhen(boolean delayError, Iterable> sourcesIterable) { this.delayError = delayError; this.sources = null; this.sourcesIterable = Objects.requireNonNull(sourcesIterable, "sourcesIterable"); } @SuppressWarnings("unchecked") @Nullable Mono whenAdditionalSource(Publisher source) { Publisher[] oldSources = sources; if (oldSources != null) { int oldLen = oldSources.length; Publisher[] newSources = new Publisher[oldLen + 1]; System.arraycopy(oldSources, 0, newSources, 0, oldLen); newSources[oldLen] = source; return new MonoWhen(delayError, newSources); } return null; } @SuppressWarnings("unchecked") @Override public void subscribe(CoreSubscriber actual) { Publisher[] a; int n = 0; if (sources != null) { a = sources; n = a.length; } else { a = new Publisher[8]; for (Publisher m : sourcesIterable) { if (n == a.length) { Publisher[] b = new Publisher[n + (n >> 2)]; System.arraycopy(a, 0, b, 0, n); a = b; } a[n++] = m; } } if (n == 0) { Operators.complete(actual); return; } WhenCoordinator parent = new WhenCoordinator(actual, n, delayError); actual.onSubscribe(parent); parent.subscribe(a); } @Override public Object scanUnsafe(Attr key) { if (key == Attr.DELAY_ERROR) return delayError; return null; } static final class WhenCoordinator extends Operators.MonoSubscriber { final WhenInner[] subscribers; final boolean delayError; volatile int done; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater DONE = AtomicIntegerFieldUpdater.newUpdater(WhenCoordinator.class, "done"); @SuppressWarnings("unchecked") WhenCoordinator(CoreSubscriber subscriber, int n, boolean delayError) { super(subscriber); this.delayError = delayError; subscribers = new WhenInner[n]; for (int i = 0; i < n; i++) { subscribers[i] = new WhenInner(this); } } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.TERMINATED) { return done == subscribers.length; } if (key == Attr.BUFFERED) { return subscribers.length; } if (key == Attr.DELAY_ERROR) { return delayError; } return super.scanUnsafe(key); } @Override public Stream inners() { return Stream.of(subscribers); } void subscribe(Publisher[] sources) { WhenInner[] a = subscribers; for (int i = 0; i < a.length; i++) { sources[i].subscribe(a[i]); } } void signalError(Throwable t) { if (delayError) { signal(); } else { int n = subscribers.length; if (DONE.getAndSet(this, n) != n) { cancel(); actual.onError(t); } } } @SuppressWarnings("unchecked") void signal() { WhenInner[] a = subscribers; int n = a.length; if (DONE.incrementAndGet(this) != n) { return; } Throwable error = null; Throwable compositeError = null; for (int i = 0; i < a.length; i++) { WhenInner m = a[i]; Throwable e = m.error; if (e != null) { if (compositeError != null) { //this is ok as the composite created below is never a singleton compositeError.addSuppressed(e); } else if (error != null) { compositeError = Exceptions.multiple(error, e); } else { error = e; } } } if (compositeError != null) { actual.onError(compositeError); } else if (error != null) { actual.onError(error); } else { actual.onComplete(); } } @Override public void cancel() { if (!isCancelled()) { super.cancel(); for (WhenInner ms : subscribers) { ms.cancel(); } } } } static final class WhenInner implements InnerConsumer { final WhenCoordinator parent; volatile Subscription s; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater S = AtomicReferenceFieldUpdater.newUpdater(WhenInner.class, Subscription.class, "s"); Throwable error; WhenInner(WhenCoordinator parent) { this.parent = parent; } @Override @Nullable public Object scanUnsafe(Attr key) { if (key == Attr.CANCELLED) { return s == Operators.cancelledSubscription(); } if (key == Attr.PARENT) { return s; } if (key == Attr.ACTUAL) { return parent; } if (key == Attr.ERROR) { return error; } return null; } @Override public Context currentContext() { return parent.currentContext(); } @Override public void onSubscribe(Subscription s) { if (Operators.setOnce(S, this, s)) { s.request(Long.MAX_VALUE); } else { s.cancel(); } } @Override public void onNext(Object t) { } @Override public void onError(Throwable t) { error = t; parent.signalError(t); } @Override public void onComplete() { parent.signal(); } void cancel() { Operators.terminate(S, this); } } } |
blob | Long method2 Feature envy3 Magic number (8)4 Nested conditionals (if/else)5 Use of null (ObjectsrequireNonNull)6 Use of unchecked annotations (@SuppressWarnings)7 Use of volatile variables8 Use of AtomicReferenceFieldUpdater9 Lack of consistent formatting and naming conventions | t | f | f | . Long method2. Feature envy3. Magic number (8)4. Nested conditionals (if/else)5. Use of null (Objects.requireNonNull)6. Use of unchecked annotations (@SuppressWarnings)7. Use of volatile variables8. Use of AtomicReferenceFieldUpdater9. Lack of consistent formatting and naming conventions | blob | 0 | 11230 | https://github.com/reactor/reactor-core/blob/3958e2fabf49e16229dda5df39e7cde46797ec51/reactor-core/src/main/java/reactor/core/publisher/MonoWhen.java/#L36-L292 | 2 | 1540 | 11230 | major |
| 1886 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | long method | t | t | f | long method | blob | 0 | 12297 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 1886 | 12297 | major |
| 155 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 1952 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 | 2 | 155 | 1952 | major |
| 1096 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { /** * @see AddDomainOptions#primaryNameServer */ public static AddDomainOptions primaryNameServer(String primaryNameServer) { return AddDomainOptions.class.cast(new AddDomainOptions().primaryNameServer(primaryNameServer)); } /** * @see AddDomainOptions#responsiblePerson */ public static AddDomainOptions responsiblePerson(String responsiblePerson) { return AddDomainOptions.class.cast(new AddDomainOptions().responsiblePerson(responsiblePerson)); } /** * @see AddDomainOptions#ttl */ public static AddDomainOptions ttl(int ttl) { return AddDomainOptions.class.cast(new AddDomainOptions().ttl(ttl)); } /** * @see AddDomainOptions#refresh */ public static AddDomainOptions refresh(int refresh) { return AddDomainOptions.class.cast(new AddDomainOptions().refresh(refresh)); } /** * @see AddDomainOptions#retry */ public static AddDomainOptions retry(int retry) { return AddDomainOptions.class.cast(new AddDomainOptions().retry(retry)); } /** * @see AddDomainOptions#expire */ public static AddDomainOptions expire(int expire) { return AddDomainOptions.class.cast(new AddDomainOptions().expire(expire)); } /** * @see AddDomainOptions#minimum */ public static AddDomainOptions minimum(int minimum) { return AddDomainOptions.class.cast(new AddDomainOptions().minimum(minimum)); } /** * @see AddDomainOptions#minimalRecords */ public static AddDomainOptions minimalRecords() { return AddDomainOptions.class.cast(new AddDomainOptions().minimalRecords()); } } |
blob | data class | t | t | f | data class | blob | 0 | 9783 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java/#L21-L77 | 1 | 1096 | 9783 | major |
| 1704 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | t | f | f | data class | 0 | 11741 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 1704 | 11741 | minor | ||
| 5431 | { "YES I found bad smells": true, "the bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | long method | t | t | f | long method | blob | 0 | 15257 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 5431 | 15257 | major |
| 625 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 6254 | https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 | 2 | 625 | 6254 | major |
| 5249 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14679 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 | 1 | 5249 | 14679 | minor |
| 1930 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12453 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 2 | 1930 | 12453 | minor |
| 628 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 6271 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 2 | 628 | 6271 | major |
| 1840 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | t | f | f | long method | 0 | 12149 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 1840 | 12149 | minor | ||
| 1336 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | f | f | f | blob | 0 | 10727 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 2 | 1336 | 10727 | minor | ||
| 1267 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | data class | t | t | f | data class | blob | 0 | 10549 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 1 | 1267 | 10549 | minor |
| 55 | { "input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example {\n private int field1;\n private String field2;\n\n public Example(int field1, String field2) {\n this.field1 = field1;\n this.field2 = field2;\n }\n\n public void doSomething() {\n if (field1 > 10) {\n System.out.println(\"Field1 is greater than 10\");\n } else {\n System.out.println(\"Field1 is not greater than 10\");\n }\n }\n}" }, "output": "YES I found bad smells\nthe bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | yes i found bad smellsthe bad smells are: 2. data class | t | t | f | yes i found bad smellsthe bad smells are: 2. data class | blob | 0 | 959 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 1 | 55 | 959 | minor |
| 50 | { "response": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRegistry public class ObjectFactory { /** * Create an instance of {@link LWM2M } * */ public LWM2M createLWM2M() { return new LWM2M(); } /** * Create an instance of {@link LWM2M.Object } * */ public LWM2M.Object createLWM2MObject() { return new LWM2M.Object(); } /** * Create an instance of {@link LWM2M.Object.Resources } * */ public LWM2M.Object.Resources createLWM2MObjectResources() { return new LWM2M.Object.Resources(); } /** * Create an instance of {@link LWM2M.Object.Resources.Item } * */ public LWM2M.Object.Resources.Item createLWM2MObjectResourcesItem() { return new LWM2M.Object.Resources.Item(); } } |
data class | long method | t | t | f | long method | data class | 0 | 866 | https://github.com/eclipse/vorto/blob/93919469e598ec07fed134536b901efd25cf674f/repository/repository-importer/importer-ipso/src/main/java/org/eclipse/vorto/repository/importer/ipso/ObjectFactory.java/#L37-L72 | 2 | 50 | 866 | major |
| 630 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 6286 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 630 | 6286 | critical |
| 1663 | {"message": "YES I found bad smells","bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 11615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1663 | 11615 | minor |
| 2550 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 14797 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 | 1 | 2550 | 14797 | major |
| 977 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 8825 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 2 | 977 | 8825 | minor |
| 170 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Long parameter list", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
data class | long method, long parameter list, feature envy | t | t | f | long method, long parameter list, feature envy | data class | 0 | 2035 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 2 | 170 | 2035 | major |
| 1713 | YES I found bad smells the bad smells are:1.Long method, 2.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; } |
blob | Long method, 2Feature envy: | t | f | f | .Long method, 2.Feature envy: | blob | 0 | 11775 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 | 2 | 1713 | 11775 | major |
| 1795 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | 'Long Method' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',o,n,g," ",M,t,h,o,d,'} | 0 | 11998 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1795 | 11998 | minor |
| 1993 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12691 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 1993 | 12691 | minor |
| 1503 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 11136 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 1503 | 11136 | minor |
| 282 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 3020 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 | 2 | 282 | 3020 | major |
| 2122 | YES I found bad smells the bad smells are: 1. Long method (createLuceneListenersAndFileChunkRegions) 2. Feature envy (isIndexingInProgress) 3. Feature envy (createRegion) 4. Duplicated code (createRegion) 5. Primitive obsession (createRegion) 6. Long method (createRegion) 7. Long parameter list (configureLuceneRegionAttributesFactory) 8. Long method (isIndexAvailable) 9. Magic numbers (LuceneServiceImpl.LUCENE_REINDEX) 10. Long method (destroy) 11. Large class (LuceneIndexForPartitionedRegion) 12. Lazy class (LuceneIndexForPartitionedRegion) 13. Long method (destroyOnRemoteMembers) 14. Message chains (getDataRegion().getDistributionManager()) 15. Long method (waitForReplies) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
data class | Long method (createLuceneListenersAndFileChunkRegions)2 Feature envy (isIndexingInProgress)3 Feature envy (createRegion)4 Duplicated code (createRegion)5 Primitive obsession (createRegion)6 Long method (createRegion)7 Long parameter list (configureLuceneRegionAttributesFactory)8 Long method (isIndexAvailable)9 Magic numbers (LuceneServiceImplLUCENE_REINDEX) | t | f | f | . Long method (createLuceneListenersAndFileChunkRegions)2. Feature envy (isIndexingInProgress)3. Feature envy (createRegion)4. Duplicated code (createRegion)5. Primitive obsession (createRegion)6. Long method (createRegion)7. Long parameter list (configureLuceneRegionAttributesFactory)8. Long method (isIndexAvailable)9. Magic numbers (LuceneServiceImpl.LUCENE_REINDEX) | data class | 0 | 13214 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 2122 | 13214 | minor |
| 209 | {"message": "YES I found bad smells the bad smells are: 1.Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ProjectList extends DataType implements Cloneable { protected ArrayList list = new ArrayList(); /** * add a project * @param pro */ public void addProjectInfo(ProjectInfo pro) { list.add(pro); } /** * get project by index * @param index * @return */ public ProjectInfo getProject(int index) { assert(index>=0 && index<list.size()); return (ProjectInfo)list.get(index); } /** * get count * @return */ public int getCount() { return list.size(); } } |
data class | 1.long method | t | t | f | 1.long method | data class | 0 | 2311 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/build/org.eclipse.birt.build/src/org/eclipse/birt/build/ProjectList.java/#L24-L61 | 2 | 209 | 2311 | minor |
| 2512 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14689 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 2512 | 14689 | major |
| 1930 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 12453 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 1930 | 12453 | minor |
| 1693 | { "output": "YES I found bad smells", "detected_bad_smells": { "1": "Long Method", "2": "Blob" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | t | f | f | long method | 0 | 11716 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 1693 | 11716 | minor | ||
| 994 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static final class SymbolComparator implements Comparator { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object arg0, Object arg1) { long addr0=0; long addr1=0; // arg0 and arg1 will be Symbol objects if (arg0 instanceof Symbol) { Symbol S0 = (Symbol) arg0; Symbol S1 = (Symbol) arg1; addr0 = S0.symbolStart; addr1 = S1.symbolStart; } else { addr0 = ((Long)arg0).longValue(); addr1 = ((Long)arg1).longValue(); } // both +ve if (addr0 >= 0 && addr1 >=0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return -1; return 1; } // both -ve if (addr0 < 0 && addr1 < 0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return 1; return -1; } if (addr0 < 0 && addr1 >=0) { return 1; } return -1; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 9091 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/Symbol.java/#L134-L175 | 1 | 994 | 9091 | minor |
| 875 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UFile { /* Not sure yet where this should be. */ static { System.loadLibrary("jtux"); } /** Java version of C struct iovec. Click {@link here} for Posix/SUS C API. */ static public class s_iovec { public byte[] iov_base; // base address of data public int iov_len; // size of this piece } /** Java version of C struct statvfs. Click {@link here} for Posix/SUS C API. */ static public class s_statvfs { public long f_bsize; // block size public long f_frsize; // fundamental (fblock) size public long f_blocks; // total number of fblocks public long f_bfree; // number of free fblocks public long f_bavail; // number of avail. fblocks public long f_files; // total number of i-numbers public long f_ffree; // number of free i-numbers public long f_favail; // number of avail. i-numbers public long f_fsid; // file-system ID public long f_flag; // flags (see below) public long f_namemax; // max length of filename } /** Java version of C struct stat. Click {@link here} for Posix/SUS C API. */ static public class s_stat { public long st_dev; // device ID of file system public int st_ino; // i-number public int st_mode; // mode (see below) public int st_nlink; // number of hard links public long st_uid; // user ID public long st_gid; // group ID public long st_rdev; // device ID (if special file) public long st_size; // size in bytes public long st_atime; // last access public long st_mtime; // last data modification public long st_ctime; // last i-node modification public int st_blksize; // optimal I/O size public long st_blocks; // allocated 512-byte blocks } /** Java version of C struct utimbuf. Click {@link here} for Posix/SUS C API. */ static public class s_utimbuf { public long actime; // access time public long modtime; // modification time } /** Java version of fd_set. */ static public class fd_set { static { System.loadLibrary("jtux"); System.out.println("Loaded"); } public byte[] set = new byte[GetSize_fd_set()]; native int GetSize_fd_set(); } /** Java version of C struct pollfd. Click {@link here} for Posix/SUS C API. */ static public class s_pollfd { public int fd; // file descriptor public short events; // input event flags public short revents; // output event flags } /** Calls access. Click {@link here} for Posix/SUS C API. */ public native static void access(String path, int what) throws UErrorException; /** Calls chmod. Click {@link here} for Posix/SUS C API. */ public native static void chmod(String path, int mode) throws UErrorException; /** Calls chown. Click {@link here} for Posix/SUS C API. */ public native static void chown(String path, long uid, long gid) throws UErrorException; /** Calls close. Click {@link here} for Posix/SUS C API. */ public native static void close(int fd) throws UErrorException; /** Does the equivalent of creat, by calling open. Click {@link here} for Posix/SUS C API. */ public static int creat(String path, int perms) throws UErrorException { return open(path, UConstant.O_WRONLY | UConstant.O_CREAT | UConstant.O_TRUNC, perms); } /** Calls dup. Click {@link here} for Posix/SUS C API. */ public native static int dup(int fd) throws UErrorException; /** Calls dup2. Click {@link here} for Posix/SUS C API. */ public native static int dup2(int fd, int fd2) throws UErrorException; /** Calls fchmod. Click {@link here} for Posix/SUS C API. */ public native static void fchmod(int fd, int mode) throws UErrorException; /** Calls fchown. Click {@link here} for Posix/SUS C API. */ public native static void fchown(int fd, long uid, long gid) throws UErrorException; /** Calls fcntl. Click {@link here} for Posix/SUS C API. */ public native static int fcntl(int fd, int op, int arg) throws UErrorException; /** Calls FD_ZERO. Click {@link here} for Posix/SUS C API. */ public native static void FD_ZERO(fd_set set); /** Calls FD_SET. Click {@link here} for Posix/SUS C API. */ public native static void FD_SET(int fd, fd_set set); /** Calls FD_CLR. Click {@link here} for Posix/SUS C API. */ public native static void FD_CLR(int fd, fd_set set); /** Calls FD_ISSET. Click {@link here} for Posix/SUS C API. */ public native static boolean FD_ISSET(int fd, fd_set set); /** Calls fdatasync. Click {@link here} for Posix/SUS C API. */ public native static void fdatasync(int fd) throws UErrorException; /** Calls fstat. Click {@link here} for Posix/SUS C API. */ public native static void fstat(int fd, s_stat buf) throws UErrorException; /** Calls fstatvfs. Click {@link here} for Posix/SUS C API. */ public native static void fstatvfs(int fd, s_statvfs buf) throws UErrorException; /** Calls fsync. Click {@link here} for Posix/SUS C API. */ public native static void fsync(int fd) throws UErrorException; /** Calls ftruncate. Click {@link here} for Posix/SUS C API. */ public native static void ftruncate(int fd, long length) throws UErrorException; /** Calls lchown. Click {@link here} for Posix/SUS C API. */ public native static void lchown(String path, long uid, long gid) throws UErrorException; /** Calls link. Click {@link here} for Posix/SUS C API. */ public native static void link(String oldpath, String newpath) throws UErrorException; /** Calls lockf. Click {@link here} for Posix/SUS C API. */ public native static void lockf(int fd, int op, long len) throws UErrorException; /** Calls lseek. Click {@link here} for Posix/SUS C API. */ public native static long lseek(int fd, long pos, int whence) throws UErrorException; /** Calls lstat. Click {@link here} for Posix/SUS C API. */ public native static void lstat(String path, s_stat buf) throws UErrorException; /** Calls mkfifo. Click {@link here} for Posix/SUS C API. */ public native static void mkfifo(String path, int perms) throws UErrorException; /** Calls mknod. Click {@link here} for Posix/SUS C API. */ public native static void mknod(String path, int mode, long dev) throws UErrorException; /** Calls mkstemp. Click {@link here} for Posix/SUS C API. */ public native static int mkstemp(StringBuffer template) throws UErrorException; /** Calls open. Click {@link here} for Posix/SUS C API. */ public native static int open(String path, int flags, int perms) throws UErrorException; /** Calls open. Click {@link here} for Posix/SUS C API. */ public static int open(String path, int flags) throws UErrorException { return open(path, flags, 0); } /** Calls pipe. Click {@link here} for Posix/SUS C API. */ public native static void pipe(int[] pfd) throws UErrorException; /** Calls poll. Click {@link here} for Posix/SUS C API. */ public native static int poll(s_pollfd[] fdinfo, int nfds, int timeout); /** Calls pread. Click {@link here} for Posix/SUS C API. */ public native static int pread(int fd, byte[] buf, int nbytes, long offset) throws UErrorException; /** Calls pselect. Click {@link here} for Posix/SUS C API. */ public native static int pselect(int nfds, fd_set readset, fd_set writeset, fd_set errorset, UProcess.s_timespec timeout, UProcess.sigset_t sigmask) throws UErrorException; /** Calls pwrite. Click {@link here} for Posix/SUS C API. */ public native static int pwrite(int fd, byte[] buf, int nbytes, long position) throws UErrorException; /** Calls read. Click {@link here} for Posix/SUS C API. */ public native static int read(int fd, byte[] buf, int nbytes) throws UErrorException; /** Calls readlink. Click {@link here} for Posix/SUS C API. */ public native static int readlink(String path, byte[] buf, int bufsize) throws UErrorException; /** Calls readv. Click {@link here} for Posix/SUS C API. */ public native static int readv(int fd, s_iovec[] iov, int iovcnt) throws UErrorException; /** Calls rename. Click {@link here} for Posix/SUS C API. */ public native static void rename(String oldpath, String newpath) throws UErrorException; /** Calls S_ISBLK. */ public native static boolean S_ISBLK(int mode); /** Calls S_ISCHR. */ public native static boolean S_ISCHR(int mode); /** Calls S_ISDIR. */ public native static boolean S_ISDIR(int mode); /** Calls S_ISFIFO. */ public native static boolean S_ISFIFO(int mode); /** Calls S_ISLNK. */ public native static boolean S_ISLNK(int mode); /** Calls S_ISREG. */ public native static boolean S_ISREG(int mode); /** Calls S_ISSOCK. */ public native static boolean S_ISSOCK(int mode); /** Calls select. Click {@link here} for Posix/SUS C API. */ public native static int select(int nfds, fd_set readset, fd_set writeset, fd_set errorset, UProcess.s_timeval timeout) throws UErrorException; /** Calls stat. Click {@link here} for Posix/SUS C API. */ public native static void stat(String path, s_stat buf) throws UErrorException; /** Calls statvfs. Click {@link here} for Posix/SUS C API. */ public native static void statvfs(String path, s_statvfs buf) throws UErrorException; /** Calls symlink. Click {@link here} for Posix/SUS C API. */ public native static void symlink(String oldpath, String newpath) throws UErrorException; /** Calls sync. Click {@link here} for Posix/SUS C API. */ public native static void sync(); /** Calls truncate. Click {@link here} for Posix/SUS C API. */ public native static void truncate(String path, long length) throws UErrorException; /** Calls unlink. Click {@link here} for Posix/SUS C API. */ public native static void unlink(String path) throws UErrorException; /** Calls utime. Click {@link here} for Posix/SUS C API. */ public native static void utime(String path, s_utimbuf timbuf) throws UErrorException; /** Calls write. Click {@link here} for Posix/SUS C API. */ /** Calls ioctl. Click {@link here} for Posix/SUS C API. */ public native static int ioctl(int fd, int request, byte[] buf) throws UErrorException; /** Calls ioctl. Click {@link here} for Posix/SUS C API. */ public native static int ioctl2(int fd, int request, int arg) throws UErrorException; /** Calls write. Click {@link here} for Posix/SUS C API. */ public native static int write(int fd, byte[] buf, int nbytes) throws UErrorException; /** Calls writev. Click {@link here} for Posix/SUS C API. */ public native static int writev(int fd, s_iovec[] iov, int iovcnt) throws UErrorException; } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 8003 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/third_party/jtux/java/jtux/UFile.java/#L29-L460 | 1 | 875 | 8003 | minor |
| 929 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Lack of encapsulation (directly setting fields instead of using methods) 4. Mixing logic with output generation in writeAsElement method 5. Not using appropriate XMLStreamWriterHelper methods in readFromElement method 6. Hard-coded type declaration in writeAsElement method 7. Magic numbers used (e.g. 2001 for xsi) 8. Potentially redundant parameterless constructor 9. Inconsistent indentation and spacing 10. Lack of comments and/or documentation 11. Potential for null pointer exceptions with unused or unassigned fields 12. Use of multiple nested if/else statements 13. Potential for duplicate code in set methods 14. Potential for duplicated or redundant code in readFromElement method 15. Lack of error handling in readFromElement method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | Long method2 Feature envy3 Lack of encapsulation (directly setting fields instead of using methods) 4 Mixing logic with output generation in writeAsElement method 5 Not using appropriate XMLStreamWriterHelper methods in readFromElement method6 Hard-coded type declaration in writeAsElement method 7 Magic numbers used (eg 200 | t | f | f | . Long method2. Feature envy3. Lack of encapsulation (directly setting fields instead of using methods) 4. Mixing logic with output generation in writeAsElement method 5. Not using appropriate XMLStreamWriterHelper methods in readFromElement method6. Hard-coded type declaration in writeAsElement method 7. Magic numbers used (e.g. 200 | data class | 0 | 8340 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 2 | 929 | 8340 | minor |
| 2403 | { "errorMessage": "Please provide the Java code snippet so that I can analyze it for common code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | Not specified | f | f | f | false | 0 | 14383 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L28634-L28646 | 1 | 2403 | 14383 | minor | |
| 266 | {"response": "YES I found bad smells", "bad_smells": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 2878 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 1 | 266 | 2878 | minor |
| 3766 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void generateReport( Locale locale, LinkcheckModel linkcheckModel ) { LinkcheckReportGenerator reportGenerator = new LinkcheckReportGenerator( i18n ); reportGenerator.setExcludedHttpStatusErrors( excludedHttpStatusErrors ); reportGenerator.setExcludedHttpStatusWarnings( excludedHttpStatusWarnings ); reportGenerator.setExcludedLinks( excludedLinks ); reportGenerator.setExcludedPages( excludedPages ); reportGenerator.setHttpFollowRedirect( httpFollowRedirect ); reportGenerator.setHttpMethod( httpMethod ); reportGenerator.setOffline( offline ); reportGenerator.generateReport( locale, linkcheckModel, getSink() ); closeReport(); // Copy the images copyStaticResources(); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 9426 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-linkcheck-plugin/src/main/java/org/apache/maven/plugins/linkcheck/LinkcheckReport.java/#L448-L465 | 2 | 3766 | 9426 | minor |
| 775 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } } |
blob | data class | t | t | f | data class | blob | 0 | 7352 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 | 1 | 775 | 7352 | minor |
| 185 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 2110 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 2 | 185 | 2110 | minor |
| 774 | YES I found bad smellsThe bad smells are: 1. Long method 2. Data class 3. Feature envy 4. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } } |
blob | Long method2 Data class3 Feature envy4 Primitive obsession | t | f | f | . Long method2. Data class3. Feature envy4. Primitive obsession | blob | 0 | 7350 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 | 2 | 774 | 7350 | major |
| 746 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class XPathFactoryFinder { private static final String DEFAULT_PACKAGE = "com.sun.org.apache.xpath.internal"; /** debug support code. */ private static boolean debug = false; static { // Use try/catch block to support applets try { debug = SecuritySupport.getSystemProperty("jaxp.debug") != null; } catch (Exception unused) { debug = false; } } /** * Cache properties for performance. */ private static final Properties cacheProps = new Properties(); /** * First time requires initialization overhead. */ private volatile static boolean firstTime = true; /** * Conditional debug printing. * * @param msgGen Supplier function that returns debug message */ private static void debugPrintln(Supplier msgGen) { if (debug) { System.err.println("JAXP: " + msgGen.get()); } } /** * ClassLoader to use to find XPathFactory. */ private final ClassLoader classLoader; /** * Constructor that specifies ClassLoader to use * to find XPathFactory. * * @param loader * to be used to load resource and {@link XPathFactory} * implementations during the resolution process. * If this parameter is null, the default system class loader * will be used. */ public XPathFactoryFinder(ClassLoader loader) { this.classLoader = loader; if( debug ) { debugDisplayClassLoader(); } } private void debugDisplayClassLoader() { try { if( classLoader == SecuritySupport.getContextClassLoader() ) { debugPrintln(() -> "using thread context class loader ("+classLoader+") for search"); return; } } catch( Throwable unused ) { // getContextClassLoader() undefined in JDK1.1 } if( classLoader==ClassLoader.getSystemClassLoader() ) { debugPrintln(() -> "using system class loader ("+classLoader+") for search"); return; } debugPrintln(() -> "using class loader ("+classLoader+") for search"); } /** * Creates a new {@link XPathFactory} object for the specified * object model. * * @param uri * Identifies the underlying object model. * * @return null if the callee fails to create one. * * @throws NullPointerException * If the parameter is null. */ public XPathFactory newFactory(String uri) throws XPathFactoryConfigurationException { if (uri == null) { throw new NullPointerException(); } XPathFactory f = _newFactory(uri); if (f != null) { debugPrintln(()->"factory '" + f.getClass().getName() + "' was found for " + uri); } else { debugPrintln(()->"unable to find a factory for " + uri); } return f; } /** * Lookup a {@link XPathFactory} for the given object model. * * @param uri identifies the object model. * * @return {@link XPathFactory} for the given object model. */ private XPathFactory _newFactory(String uri) throws XPathFactoryConfigurationException { XPathFactory xpathFactory = null; String propertyName = SERVICE_CLASS.getName() + ":" + uri; // system property look up try { debugPrintln(()->"Looking up system property '"+propertyName+"'" ); String r = SecuritySupport.getSystemProperty(propertyName); if(r!=null) { debugPrintln(()->"The value is '"+r+"'"); xpathFactory = createInstance(r); if (xpathFactory != null) { return xpathFactory; } } else debugPrintln(()->"The property is undefined."); } catch( Throwable t ) { if( debug ) { debugPrintln(()->"failed to look up system property '"+propertyName+"'" ); t.printStackTrace(); } } String javah = SecuritySupport.getSystemProperty( "java.home" ); String configFile = javah + File.separator + "conf" + File.separator + "jaxp.properties"; // try to read from $java.home/conf/jaxp.properties try { if(firstTime){ synchronized(cacheProps){ if(firstTime){ File f=new File( configFile ); firstTime = false; if(SecuritySupport.doesFileExist(f)){ debugPrintln(()->"Read properties file " + f); cacheProps.load(SecuritySupport.getFileInputStream(f)); } } } } final String factoryClassName = cacheProps.getProperty(propertyName); debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties"); if (factoryClassName != null) { xpathFactory = createInstance(factoryClassName); if(xpathFactory != null){ return xpathFactory; } } } catch (Exception ex) { if (debug) { ex.printStackTrace(); } } // Try with ServiceLoader assert xpathFactory == null; xpathFactory = findServiceProvider(uri); // The following assertion should always be true. // Uncomment it, recompile, and run with -ea in case of doubts: // assert xpathFactory == null || xpathFactory.isObjectModelSupported(uri); if (xpathFactory != null) { return xpathFactory; } // platform default if(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) { debugPrintln(()->"attempting to use the platform default W3C DOM XPath lib"); return new XPathFactoryImpl(); } debugPrintln(()->"all things were tried, but none was found. bailing out."); return null; } /** Create class using appropriate ClassLoader. * * @param className Name of class to create. * @return Created class or null. */ private Class createClass(String className) { Class clazz; // make sure we have access to restricted packages boolean internal = false; if (System.getSecurityManager() != null) { if (className != null && className.startsWith(DEFAULT_PACKAGE)) { internal = true; } } // use approprite ClassLoader try { if (classLoader != null && !internal) { clazz = Class.forName(className, false, classLoader); } else { clazz = Class.forName(className); } } catch (Throwable t) { if(debug) { t.printStackTrace(); } return null; } return clazz; } /** * Creates an instance of the specified and returns it. * * @param className * fully qualified class name to be instantiated. * * @return null * if it fails. Error messages will be printed by this method. */ XPathFactory createInstance(String className) throws XPathFactoryConfigurationException { XPathFactory xPathFactory = null; debugPrintln(()->"createInstance(" + className + ")"); // get Class from className Class clazz = createClass(className); if (clazz == null) { debugPrintln(()->"failed to getClass(" + className + ")"); return null; } debugPrintln(()->"loaded " + className + " from " + which(clazz)); // instantiate Class as a XPathFactory try { xPathFactory = (XPathFactory) clazz.getConstructor().newInstance(); } catch (ClassCastException | IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { debugPrintln(()->"could not instantiate " + clazz.getName()); if (debug) { ex.printStackTrace(); } return null; } return xPathFactory; } // Call isObjectModelSupportedBy with initial context. private boolean isObjectModelSupportedBy(final XPathFactory factory, final String objectModel, AccessControlContext acc) { return AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { return factory.isObjectModelSupported(objectModel); } }, acc); } /** * Finds a service provider subclass of XPathFactory that supports the * given object model using the ServiceLoader. * * @param objectModel URI of object model to support. * @return An XPathFactory supporting the specified object model, or null * if none is found. * @throws XPathFactoryConfigurationException if a configuration error is found. */ private XPathFactory findServiceProvider(final String objectModel) throws XPathFactoryConfigurationException { assert objectModel != null; // store current context. final AccessControlContext acc = AccessController.getContext(); try { return AccessController.doPrivileged(new PrivilegedAction() { public XPathFactory run() { final ServiceLoader loader = ServiceLoader.load(SERVICE_CLASS); for (XPathFactory factory : loader) { // restore initial context to call // factory.isObjectModelSupportedBy if (isObjectModelSupportedBy(factory, objectModel, acc)) { return factory; } } return null; // no factory found. } }); } catch (ServiceConfigurationError error) { throw new XPathFactoryConfigurationException(error); } } private static final Class SERVICE_CLASS = XPathFactory.class; // Used for debugging purposes private static String which( Class clazz ) { return SecuritySupport.getClassSource(clazz); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7014 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java/#L46-L357 | 1 | 746 | 7014 | major |
| 2383 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 14341 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 1 | 2383 | 14341 | minor |
| 1971 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12608 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 | 1 | 1971 | 12608 | major |
| 3543 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } } |
blob | data class | t | t | f | data class | blob | 0 | 7716 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 | 1 | 3543 | 7716 | major |
| 2090 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive logging 4. Inconsistent indentation 5. Inefficient handling of exceptions 6. Magic numbers 7. Lack of encapsulation 8. Poor naming/meaningful variable names 9. Code duplication 10. Mixed levels of abstraction. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BatchWriterReplicationReplayer implements AccumuloReplicationReplayer { private static final Logger log = LoggerFactory.getLogger(BatchWriterReplicationReplayer.class); @Override public long replicateLog(ClientContext context, String tableName, WalEdits data) throws RemoteReplicationException { final LogFileKey key = new LogFileKey(); final LogFileValue value = new LogFileValue(); final long memoryInBytes = context.getConfiguration() .getAsBytes(Property.TSERV_REPLICATION_BW_REPLAYER_MEMORY); BatchWriter bw = null; long mutationsApplied = 0L; try { for (ByteBuffer edit : data.getEdits()) { DataInputStream dis = new DataInputStream(ByteBufferUtil.toByteArrayInputStream(edit)); try { key.readFields(dis); // TODO this is brittle because AccumuloReplicaSystem isn't actually calling // LogFileValue.write, but we're expecting // what we receive to be readable by the LogFileValue. value.readFields(dis); } catch (IOException e) { log.error("Could not deserialize edit from stream", e); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_DESERIALIZE, "Could not deserialize edit from stream"); } // Create the batchScanner if we don't already have one. if (bw == null) { BatchWriterConfig bwConfig = new BatchWriterConfig(); bwConfig.setMaxMemory(memoryInBytes); try { bw = context.createBatchWriter(tableName, bwConfig); } catch (TableNotFoundException e) { throw new RemoteReplicationException(RemoteReplicationErrorCode.TABLE_DOES_NOT_EXIST, "Table " + tableName + " does not exist"); } } log.info("Applying {} mutations to table {} as part of batch", value.mutations.size(), tableName); // If we got a ServerMutation, we have to make sure that we preserve the systemTimestamp // otherwise // the local system will assign a new timestamp. List mutationsCopy = new ArrayList<>(value.mutations.size()); long mutationsCopied = 0L; for (Mutation orig : value.mutations) { if (orig instanceof ServerMutation) { mutationsCopied++; ServerMutation origServer = (ServerMutation) orig; Mutation copy = new Mutation(orig.getRow()); for (ColumnUpdate update : orig.getUpdates()) { long timestamp; // If the update doesn't have a timestamp, pull it from the ServerMutation if (!update.hasTimestamp()) { timestamp = origServer.getSystemTimestamp(); } else { timestamp = update.getTimestamp(); } // TODO ACCUMULO-2937 cache the CVs if (update.isDeleted()) { copy.putDelete(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp); } else { copy.put(update.getColumnFamily(), update.getColumnQualifier(), new ColumnVisibility(update.getColumnVisibility()), timestamp, update.getValue()); } } // We also need to preserve the replicationSource information to prevent cycles Set replicationSources = orig.getReplicationSources(); if (replicationSources != null && !replicationSources.isEmpty()) { for (String replicationSource : replicationSources) { copy.addReplicationSource(replicationSource); } } mutationsCopy.add(copy); } else { mutationsCopy.add(orig); } } log.debug("Copied {} mutations to ensure server-assigned timestamps are propagated", mutationsCopied); try { bw.addMutations(mutationsCopy); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } log.debug("{} mutations added to the BatchScanner", mutationsCopy.size()); mutationsApplied += mutationsCopy.size(); } } finally { if (bw != null) { try { bw.close(); } catch (MutationsRejectedException e) { log.error("Could not apply mutations to {}", tableName); throw new RemoteReplicationException(RemoteReplicationErrorCode.COULD_NOT_APPLY, "Could not apply mutations to " + tableName); } } } log.info("Applied {} mutations in total to {}", mutationsApplied, tableName); return mutationsApplied; } } |
blob | Long method2 Feature envy 3 Excessive logging 4 Inconsistent indentation 5 Inefficient handling of exceptions 6 Magic numbers 7 Lack of encapsulation 8 Poor naming/meaningful variable names 9 Code duplication | t | f | f | . Long method2. Feature envy 3. Excessive logging 4. Inconsistent indentation 5. Inefficient handling of exceptions 6. Magic numbers 7. Lack of encapsulation 8. Poor naming/meaningful variable names 9. Code duplication | blob | 0 | 13120 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/tserver/src/main/java/org/apache/accumulo/tserver/replication/BatchWriterReplicationReplayer.java/#L50-L171 | 2 | 2090 | 13120 | minor |
| 2152 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13294 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 2 | 2152 | 13294 | minor |
| 832 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component("aws-ddbstream") public class DdbStreamComponent extends DefaultComponent { @Metadata private String accessKey; @Metadata private String secretKey; @Metadata private String region; @Metadata(label = "advanced") private DdbStreamConfiguration configuration; public DdbStreamComponent() { this(null); } public DdbStreamComponent(CamelContext context) { super(context); this.configuration = new DdbStreamConfiguration(); registerExtension(new DdbStreamComponentVerifierExtension()); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { DdbStreamConfiguration configuration = this.configuration.copy(); configuration.setTableName(remaining); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Table name must be specified."); } configuration.setTableName(remaining); if (ObjectHelper.isEmpty(configuration.getAccessKey())) { setAccessKey(accessKey); } if (ObjectHelper.isEmpty(configuration.getSecretKey())) { setSecretKey(secretKey); } if (ObjectHelper.isEmpty(configuration.getRegion())) { setRegion(region); } if (configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("amazonDDBStreamsClient or accessKey and secretKey must be specified"); } DdbStreamEndpoint endpoint = new DdbStreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); return endpoint; } public DdbStreamConfiguration getConfiguration() { return configuration; } /** * The AWS DDB stream default configuration */ public void setConfiguration(DdbStreamConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return configuration.getAccessKey(); } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { configuration.setAccessKey(accessKey); } public String getSecretKey() { return configuration.getSecretKey(); } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { configuration.setSecretKey(secretKey); } public String getRegion() { return configuration.getRegion(); } /** * Amazon AWS Region */ public void setRegion(String region) { configuration.setRegion(region); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7739 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamComponent.java/#L28-L122 | 2 | 832 | 7739 | minor |
| 272 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Magic number" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class AffineMatrix implements ExtendedPrecisionMatrix, Serializable, Cloneable { /** * For cross-version compatibility. */ private static final long serialVersionUID = 1605578645060388327L; /** * The number of rows and columns of this matrix. */ private static final int SIZE = 3; /** * The length of an array containing all matrix elements. */ private static final int LENGTH = SIZE * SIZE; /** * The length of an array containing only the matrix elements to be stored. * The last row is omitted because it is assumed to contain (0 0 1). */ private static final int LENGTH_STORED = (SIZE - 1) * SIZE; /** * The length of an array containing all matrix elements together with error terms. */ private static final int LENGTH_EXTENDED = 2 * LENGTH; /** * The transform from which to get the matrix terms. */ private final AffineTransform transform; /** * The error terms, or {@code null} if none. * If non-null, then the length of this array shall be 6. */ private final double[] errors; /** * Creates a new matrix wrapping the given transform. * * @param transform the transform to wrap. * @param elements the elements used for creating the matrix (optionally with error terms), or {@code null}. */ AffineMatrix(final AffineTransform transform, final double[] elements) { this.transform = transform; if (elements != null) { assert elements.length == LENGTH || elements.length == LENGTH_EXTENDED; if (elements.length == LENGTH_EXTENDED) { errors = Arrays.copyOfRange(elements, LENGTH, LENGTH + LENGTH_STORED); /* * At this point we could check: * * assert Arrays.equals(elements, getExtendedElements()); * * but we do not, because the terms in the last row may not be exactly 0 or 1 * because of rounding errors. */ return; } } errors = null; } /** * Gets the number of rows in the matrix. */ @Override public int getNumRow() { return SIZE; } /** * Gets the number of columns in the matrix. */ @Override public int getNumCol() { return SIZE; } /** * Returns {@code true} if the backing affine transform is the identity transform. */ @Override public boolean isIdentity() { return transform.isIdentity(); } /** * Returns all matrix elements. */ @Override public double[] getExtendedElements() { final double[] elements = new double[errors != null ? LENGTH_EXTENDED : LENGTH]; if (errors != null) { System.arraycopy(errors, 0, elements, LENGTH, LENGTH_STORED); } elements[0] = transform.getScaleX(); elements[1] = transform.getShearX(); elements[2] = transform.getTranslateX(); elements[3] = transform.getShearY(); elements[4] = transform.getScaleY(); elements[5] = transform.getTranslateY(); elements[8] = 1; return elements; } /** * Returns the matrix element at the given index. */ @Override public final double getElement(final int row, final int column) { ArgumentChecks.ensureBetween("row", 0, SIZE, row); ArgumentChecks.ensureBetween("column", 0, SIZE, column); switch (row * SIZE + column) { case 0: return transform.getScaleX(); case 1: return transform.getShearX(); case 2: return transform.getTranslateX(); case 3: return transform.getShearY(); case 4: return transform.getScaleY(); case 5: return transform.getTranslateY(); case 6: // Fallthrough case 7: return 0; case 8: return 1; default: throw new AssertionError(); } } /** * Unsupported operation, since this matrix is unmodifiable. */ @Override public final void setElement(final int row, final int column, final double value) { throw new UnsupportedOperationException(Resources.format(Resources.Keys.UnmodifiableAffineTransform)); } /** * Returns a copy of the matrix that user can modify. */ @Override @SuppressWarnings("CloneDoesntCallSuperClone") public final Matrix clone() { return Matrices.copy(this); } /** * Compares this matrix with the given object for equality, including error terms (if any). */ @Override public boolean equals(final Object obj) { if (obj instanceof AffineMatrix) { final AffineMatrix other = (AffineMatrix) obj; return transform.equals(other.transform) && Arrays.equals(errors, other.errors); } return false; } /** * Returns a hash code value for this matrix. */ @Override public int hashCode() { return (transform.hashCode() * 31 + Arrays.hashCode(errors)) ^ (int) serialVersionUID; } /** * Returns a string representation of this matrix. * * @return a string representation of this matrix. */ @Override public String toString() { return Matrices.toString(this); } } |
blob | long method, magic number | t | t | f | long method, magic number | blob | 0 | 2924 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/j2d/AffineMatrix.java/#L38-L212 | 2 | 272 | 2924 | minor |
| 2020 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12785 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 2020 | 12785 | major |
| 2174 | {"answer": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } } |
blob | Long Method"} | t | f | f | . Long Method"} | blob | 0 | 13387 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 | 1 | 2174 | 13387 | minor |
| 2320 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WordMedian extends Configured implements Tool { private double median = 0; private final static IntWritable ONE = new IntWritable(1); /** * Maps words from line of text into a key-value pair; the length of the word * as the key, and 1 as the value. */ public static class WordMedianMapper extends Mapper { private IntWritable length = new IntWritable(); /** * Emits a key-value pair for counting the word. Outputs are (IntWritable, * IntWritable). * * @param value * This will be a line of text coming in from our input file. */ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { String string = itr.nextToken(); length.set(string.length()); context.write(length, ONE); } } } /** * Performs integer summation of all the values for each key. */ public static class WordMedianReducer extends Reducer { private IntWritable val = new IntWritable(); /** * Sums all the individual values within the iterator and writes them to the * same key. * * @param key * This will be a length of a word that was read. * @param values * This will be an iterator of all the values associated with that * key. */ public void reduce(IntWritable key, Iterable values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } val.set(sum); context.write(key, val); } } /** * This is a standard program to read and find a median value based on a file * of word counts such as: 1 456, 2 132, 3 56... Where the first values are * the word lengths and the following values are the number of times that * words of that length appear. * * @param path * The path to read the HDFS file from (part-r-00000...00001...etc). * @param medianIndex1 * The first length value to look for. * @param medianIndex2 * The second length value to look for (will be the same as the first * if there are an even number of words total). * @throws IOException * If file cannot be found, we throw an exception. * */ private double readAndFindMedian(String path, int medianIndex1, int medianIndex2, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); Path file = new Path(path, "part-r-00000"); if (!fs.exists(file)) throw new IOException("Output not found!"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8)); int num = 0; String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); // grab length String currLen = st.nextToken(); // grab count String lengthFreq = st.nextToken(); int prevNum = num; num += Integer.parseInt(lengthFreq); if (medianIndex2 >= prevNum && medianIndex1 <= num) { System.out.println("The median is: " + currLen); br.close(); return Double.parseDouble(currLen); } else if (medianIndex2 >= prevNum && medianIndex1 < num) { String nextCurrLen = st.nextToken(); double theMedian = (Integer.parseInt(currLen) + Integer .parseInt(nextCurrLen)) / 2.0; System.out.println("The median is: " + theMedian); br.close(); return theMedian; } } } finally { if (br != null) { br.close(); } } // error, no median found return -1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new WordMedian(), args); } @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: wordmedian "); return 0; } setConf(new Configuration()); Configuration conf = getConf(); @SuppressWarnings("deprecation") Job job = new Job(conf, "word median"); job.setJarByClass(WordMedian.class); job.setMapperClass(WordMedianMapper.class); job.setCombinerClass(WordMedianReducer.class); job.setReducerClass(WordMedianReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean result = job.waitForCompletion(true); // Wait for JOB 1 -- get middle value to check for Median long totalWords = job.getCounters() .getGroup(TaskCounter.class.getCanonicalName()) .findCounter("MAP_OUTPUT_RECORDS", "Map output records").getValue(); int medianIndex1 = (int) Math.ceil((totalWords / 2.0)); int medianIndex2 = (int) Math.floor((totalWords / 2.0)); median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf); return (result ? 0 : 1); } public double getMedian() { return median; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 14128 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/WordMedian.java/#L43-L212 | 1 | 2320 | 14128 | minor |
| 1774 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 11932 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 2 | 1774 | 11932 | minor |
| 1032 | {"message": "YES I found bad smells"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
feature envy | Not specified | f | f | f | false | 0 | 9387 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1032 | 9387 | minor | |
| 1527 | YES I found bad smells the bad smells are: 1. Long method 2. No comments or documentation 3. Use of abstract class with only one concrete subclass 4. Use of raw types in superclass 5. Redundant use of final keyword 6. Lack of information in variable names (e.g. "source", "messageId") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Long method2 No comments or documentation3 Use of abstract class with only one concrete subclass4 Use of raw types in superclass5 Redundant use of final keyword6 Lack of information in variable names (eg "source", "messageId") | t | f | f | . Long method2. No comments or documentation3. Use of abstract class with only one concrete subclass4. Use of raw types in superclass5. Redundant use of final keyword6. Lack of information in variable names (e.g. "source", "messageId") | data class | 0 | 11193 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 1527 | 11193 | minor |
| 1157 | //(=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) rhs=BitwiseORExpression)* public Group getGroup_1() { return cGroup_1; } // => ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) public Group getGroup_1_0() { return cGroup_1_0; } public class LogicalANDExpressionElements { YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | () { return cGroup_ | t | f | f | () { return cGroup_ | data class | 0 | 10144 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 1157 | 10144 | critical |
| 364 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ContentVisitor implements IContentVisitor { public Object visit( IContent content, Object value ) { return visitContent( content, value ); } public Object visitContent( IContent content, Object value ) { boolean isInline = PropertyUtil.isInlineElement( content ); if ( isInline ) { return new InlineBlockLayout( context, parent, content ); } else { return new BlockStackingLayout( context, parent, content); } } public Object visitPage( IPageContent page, Object value ) { return new PageLayout(executor, context, parent, page); } public Object visitContainer( IContainerContent container, Object value ) { boolean isInline = PropertyUtil.isInlineElement( container ); if ( isInline ) { return new InlineContainerLayout( context, parent, container); } else { return new BlockStackingLayout( context, parent, container); } } public Object visitTable( ITableContent table, Object value ) { return new TableLayout( context, parent, table ); } public Object visitTableBand( ITableBandContent tableBand, Object value ) { return new TableBandLayout( context, parent, tableBand); } public Object visitRow( IRowContent row, Object value ) { return new RowLayout( context, parent, row ); } public Object visitCell( ICellContent cell, Object value ) { return new CellLayout( context, parent, cell ); } public Object visitText( ITextContent text, Object value ) { // FIXME return handleText( text ); } public Object visitLabel( ILabelContent label, Object value ) { return handleText( label ); } public Object visitData( IDataContent data, Object value ) { return handleText( data ); } public Object visitImage( IImageContent image, Object value ) { return new ImageLayout( context, parent, image ); } public Object visitForeign( IForeignContent foreign, Object value ) { boolean isInline = PropertyUtil.isInlineElement( foreign ); if ( isInline ) { return new InlineContainerLayout( context, parent, foreign); } else { return new BlockStackingLayout( context, parent, foreign); } } public Object visitAutoText( IAutoTextContent autoText, Object value ) { int type = autoText.getType( ); if ( type == IAutoTextContent.TOTAL_PAGE || type == IAutoTextContent.UNFILTERED_TOTAL_PAGE ) { context.addUnresolvedContent( autoText ); return new TemplateLayout( context, parent, autoText ); } return handleText( autoText ); } private Object handleText( ITextContent content ) { boolean isInline = parent instanceof IInlineStackingLayout; if ( isInline ) { return new InlineTextLayout( context, parent, content ); } else { String text = content.getText( ); if ( text == null || "".equals( text ) ) //$NON-NLS-1$ { content.setText( " " ); //$NON-NLS-1$ } return new BlockTextLayout( context, parent, content); } } public Object visitList( IListContent list, Object value ) { return new ListLayout( context, parent, list ); } public Object visitListBand( IListBandContent listBand, Object value ) { assert ( false ); return null; // return new PDFListBandLM(context, parent, listBand, emitter, // executor); } public Object visitListGroup( IListGroupContent group, Object value ) { return new ListGroupLayout( context, parent, group ); } public Object visitTableGroup( ITableGroupContent group, Object value ) { return new TableGroupLayout( context, parent, group ); } public Object visitGroup( IGroupContent group, Object value ) { return new BlockStackingLayout( context, parent, group ); } } |
blob | long method | t | t | f | long method | blob | 0 | 3715 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/emitter/LayoutContextFactory.java/#L73-L226 | 1 | 364 | 3715 | minor |
| 267 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 2884 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 2 | 267 | 2884 | minor |
| 2496 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | long method | t | t | f | long method | data class | 0 | 14641 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 2496 | 14641 | minor |
| 3728 | {"response":"YES I found bad smells","the bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 9201 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 | 2 | 3728 | 9201 | minor |
| 126 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Long parameter list", "Long class"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | long method, long parameter list, long class | t | t | f | long method, long parameter list, long class | blob | 0 | 1575 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 2 | 126 | 1575 | minor |
| 180 | { "message": "YES, I found bad smells", "the bad smells are:": [ "Long method", "Data class", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
blob | long method, data class, feature envy | t | t | f | long method, data class, feature envy | blob | 0 | 2063 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 180 | 2063 | major |
| 3834 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 9880 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 3834 | 9880 | minor |
| 2363 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 14254 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 2 | 2363 | 14254 | critical |
| 2052 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 12902 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 2 | 2052 | 12902 | minor |
| 1480 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy | data class | 0 | 11078 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 1480 | 11078 | major |
| 3572 | of the smell seems working I see that sniffs corrected NO; I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 7855 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 | 2 | 3572 | 7855 | major | ||
| 472 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 4574 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 2 | 472 | 4574 | major |
| 100 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class TraceableHttpServletResponse implements TraceableResponse { private final HttpServletResponse delegate; TraceableHttpServletResponse(HttpServletResponse response) { this.delegate = response; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return extractHeaders(); } private Map> extractHeaders() { Map> headers = new LinkedHashMap<>(); for (String name : this.delegate.getHeaderNames()) { headers.put(name, new ArrayList<>(this.delegate.getHeaders(name))); } return headers; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1304 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletResponse.java/#L33-L59 | 2 | 100 | 1304 | minor |
| 2208 | {"YES I found bad smells":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
blob | Not specified | f | f | f | ["Data Class"]} | false | 0 | 13516 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 2208 | 13516 | minor |
| 1586 | Yes, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11369 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 2 | 1586 | 11369 | major |
| 1165 | YES, I found bad smells. the bad smells are: 1. Long method 2. Class data should be private | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | Long method2 Class data should be private | t | f | f | . Long method2. Class data should be private | data class | 0 | 10183 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 1165 | 10183 | minor |
| 2027 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public IAnnulusWedgeCriteria create() { switch (this) { case LEAF_NUMBER: return new AnnulusWedgeByLeafs(); case NODE_SIZE: return new AnnulusWedgeByNodeSpace(); default: throw new IllegalArgumentException( "No implementation is available for the layout option " + this.toString()); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 12805 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.radial/src/org/eclipse/elk/alg/radial/options/AnnulusWedgeCriteria.java/#L37-L47 | 1 | 2027 | 12805 | major |
| 1562 | YES I found bad smells. The bad smells are: 1. Long parameter list. 2. Primitive obsession. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long parameter list 2 Primitive obsession | t | f | f | . Long parameter list. 2. Primitive obsession. | data class | 0 | 11312 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 1562 | 11312 | minor |
| 1658 | YES I found bad smells the bad smells are: 1. Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL 2. Unnecessary use of "protected" modifier for the class 3. Confusing and unclear comments 4. Inconsistent formatting and spacing 5. Poor variable naming (ex. prev, next, v) 6. Direct access of instance variables without encapsulation or getter/setter methods 7. Unused methods (setPrev, setNext) 8. Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity. 9. Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex. However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL2 Unnecessary use of "protected" modifier for the class3 Confusing and unclear comments4 Inconsistent formatting and spacing5 Poor variable naming (ex prev, next, v) 6 Direct access of instance variables without encapsulation or getter/setter methods7 Unused methods (setPrev, setNext)8 Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity9 Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain | t | f | f | . Duplication of code between PersistenceWithIntOffset and PersistenceWithIntOffsetNoLL2. Unnecessary use of "protected" modifier for the class3. Confusing and unclear comments4. Inconsistent formatting and spacing5. Poor variable naming (ex. prev, next, v) 6. Direct access of instance variables without encapsulation or getter/setter methods7. Unused methods (setPrev, setNext)8. Potential for Feature Envy - PersistenceWithIntOffset has direct access to and modifies the instance variables of DiskEntry, which could be considered a separate entity.9. Potential for Long Method - depending on the functionality being performed in the methods, they may be lengthy and complex. However, without a clear understanding of the context and purpose of this code, it is difficult to determine for certain. | data class | 0 | 11602 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 2 | 1658 | 11602 | minor |
| 2248 | { "input_code": "public class Calculator {\n public int sum(int a, int b) {\n int result = a + b;\n return result;\n }\n\n public int multiply(int a, int b) {\n int result = 0;\n for (int i = 0; i < b; i++) {\n result += a;\n }\n return result;\n }\n}", "detected_smells": { "Blob": false, "Data Class": false, "Feature Envy": false, "Long Method": true } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | false | 0 | 13661 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 2248 | 13661 | minor | ||
| 5745 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | f | f | f | feature envy | 0 | 14138 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5745 | 14138 | minor | ||
| 1005 | YES I found bad smellsthe bad smells are:1. Code duplication, 2. Long method, 3. Switch statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | Code duplication, 2 Long method, 3 Switch statements | t | f | f | . Code duplication, 2. Long method, 3. Switch statements. | feature envy | 0 | 9255 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1005 | 9255 | minor |
| 2096 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 13148 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 1 | 2096 | 13148 | minor |
| 2176 | YES, I found bad smells. 1. Long method, 2. Feature envy. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long method, 2 Feature envythe bad smells are: | t | f | f | . Long method, 2. Feature envy.the bad smells are: | data class | 0 | 13404 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2176 | 13404 | minor |
| 1724 | YES I found bad smells the bad smells are: 1. Missing documentation 2. Long method 3. Feature envy 4. Inefficient hashCode() and equals() methods 5. Poorly named variables (left, right) 6. Empty TODO comments 7. Class is not properly abstract as it contains some method implementations 8. Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods. 9. Possible violation of coding conventions (method names should start with lowercase) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Missing documentation2 Long method3 Feature envy4 Inefficient hashCode() and equals() methods5 Poorly named variables (left, right)6 Empty TODO comments7 Class is not properly abstract as it contains some method implementations8 Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods9 Possible violation of coding conventions (method names should start with lowercase) | t | f | f | . Missing documentation2. Long method3. Feature envy4. Inefficient hashCode() and equals() methods5. Poorly named variables (left, right)6. Empty TODO comments7. Class is not properly abstract as it contains some method implementations8. Lack of proper encapsulation, as the setters are public and can be accessed directly instead of through methods.9. Possible violation of coding conventions (method names should start with lowercase) | data class | 0 | 11803 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 1724 | 11803 | minor |
| 2288 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | f | f | f | data class | 0 | 13898 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2288 | 13898 | major | ||
| 1823 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class GoIntoAction extends ProjectAction { private final ProjectExplorerPresenter projectExplorer; private final CoreLocalizationConstant localizationConstant; @Inject public GoIntoAction( ProjectExplorerPresenter projectExplorer, CoreLocalizationConstant localizationConstant) { super(localizationConstant.goIntoActionText()); this.projectExplorer = projectExplorer; this.localizationConstant = localizationConstant; } /** {@inheritDoc} */ @Override protected void updateProjectAction(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { e.getPresentation().setText(localizationConstant.goBackActionText()); e.getPresentation().setEnabledAndVisible(true); return; } e.getPresentation().setText(localizationConstant.goIntoActionText()); List selection = projectExplorer.getSelection().getAllElements(); e.getPresentation() .setEnabledAndVisible( !projectExplorer.isGoIntoActivated() && selection.size() == 1 && isNodeSupportGoInto(selection.get(0))); } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (projectExplorer.isGoIntoActivated()) { projectExplorer.goBack(); return; } List selection = projectExplorer.getSelection().getAllElements(); if (selection.isEmpty() || selection.size() > 1) { throw new IllegalArgumentException("Node isn't selected"); } Object node = selection.get(0); if (isNodeSupportGoInto(node)) { projectExplorer.goInto((Node) node); } } private boolean isNodeSupportGoInto(Object node) { return node instanceof Node && ((Node) node).supportGoInto(); } } |
blob | Long Method | t | f | f | Long Method | blob | 0 | 12103 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/GoIntoAction.java/#L29-L88 | 1 | 1823 | 12103 | minor |
| 2576 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } } |
blob | long method | t | t | f | long method | blob | 0 | 14917 | https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 | 1 | 2576 | 14917 | minor |
| 4110 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 10825 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 2 | 4110 | 10825 | major |
| 2099 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13157 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 2099 | 13157 | minor |
| 1518 | {"response": "YES, I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | t | f | f | long method | 0 | 11170 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 1518 | 11170 | minor | ||
| 349 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataProvider { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MetadataProvider.class); private static final String IN_FUNCTION = "in"; private static final String LIKE_FUNCTION = "like"; private static final String AND_FUNCTION = "booleanand"; private static final String OR_FUNCTION = "booleanor"; /** * @return Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ public static Runnable catalogs(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { return new CatalogsProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the schema metadata for given {@link GetSchemasReq} and sends response at the end. */ public static Runnable schemas(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { return new SchemasProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the table metadata for given {@link GetTablesReq} and sends response at the end. */ public static Runnable tables(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { return new TablesProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the column metadata for given {@link GetColumnsReq} and sends response at the end. */ public static Runnable columns(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { return new ColumnsProvider(session, dContext, req, responseSender); } /** * Super class for all metadata provider runnable classes. */ private abstract static class MetadataRunnable implements Runnable { protected final UserSession session; private final ResponseSender responseSender; private final DrillbitContext dContext; private MetadataRunnable(final UserSession session, final DrillbitContext dContext, final ResponseSender responseSender) { this.session = Preconditions.checkNotNull(session); this.dContext = Preconditions.checkNotNull(dContext); this.responseSender = Preconditions.checkNotNull(responseSender); } @Override public void run() { try(SchemaTreeProvider schemaTreeProvider = new SchemaTreeProvider(dContext)) { responseSender.send(runInternal(session, schemaTreeProvider)); } catch (final Throwable error) { logger.error("Unhandled metadata provider error", error); } } /** * @return A {@link Response} message. Response must be returned in any case. */ protected abstract Response runInternal(UserSession session, SchemaTreeProvider schemaProvider); public DrillConfig getConfig() { return dContext.getConfig(); } } /** * Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ private static class CatalogsProvider extends MetadataRunnable { private static final Ordering CATALOGS_ORDERING = new Ordering() { @Override public int compare(CatalogMetadata left, CatalogMetadata right) { return Ordering.natural().compare(left.getCatalogName(), right.getCatalogName()); } }; private final GetCatalogsReq req; public CatalogsProvider(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetCatalogsResp.Builder respBuilder = GetCatalogsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(CATALOGS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Catalog c : records) { final CatalogMetadata.Builder catBuilder = CatalogMetadata.newBuilder(); catBuilder.setCatalogName(c.CATALOG_NAME); catBuilder.setDescription(c.CATALOG_DESCRIPTION); catBuilder.setConnect(c.CATALOG_CONNECT); metadata.add(catBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, CATALOGS_ORDERING); respBuilder.addAllCatalogs(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get catalogs", e)); } finally { return new Response(RpcType.CATALOGS, respBuilder.build()); } } } private static class SchemasProvider extends MetadataRunnable { private static final Ordering SCHEMAS_ORDERING = new Ordering() { @Override public int compare(SchemaMetadata left, SchemaMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .result(); }; }; private final GetSchemasReq req; private SchemasProvider(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetSchemasResp.Builder respBuilder = GetSchemasResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(SCHEMATA, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Schema s : records) { final SchemaMetadata.Builder schemaBuilder = SchemaMetadata.newBuilder(); schemaBuilder.setCatalogName(s.CATALOG_NAME); schemaBuilder.setSchemaName(s.SCHEMA_NAME); schemaBuilder.setOwner(s.SCHEMA_OWNER); schemaBuilder.setType(s.TYPE); schemaBuilder.setMutable(s.IS_MUTABLE); metadata.add(schemaBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, SCHEMAS_ORDERING); respBuilder.addAllSchemas(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get schemas", e)); } finally { return new Response(RpcType.SCHEMAS, respBuilder.build()); } } } private static class TablesProvider extends MetadataRunnable { private static final Ordering TABLES_ORDERING = new Ordering() { @Override public int compare(TableMetadata left, TableMetadata right) { return ComparisonChain.start() .compare(left.getType(), right.getType()) .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .result(); } }; private final GetTablesReq req; private TablesProvider(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, req.getTableTypeFilterCount() != 0 ? req.getTableTypeFilterList() : null, null); try { final PojoRecordReader records = getPojoRecordReader(TABLES, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Table t : records) { final TableMetadata.Builder tableBuilder = TableMetadata.newBuilder(); tableBuilder.setCatalogName(t.TABLE_CATALOG); tableBuilder.setSchemaName(t.TABLE_SCHEMA); tableBuilder.setTableName(t.TABLE_NAME); tableBuilder.setType(t.TABLE_TYPE); metadata.add(tableBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, TABLES_ORDERING); respBuilder.addAllTables(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get tables", e)); } finally { return new Response(RpcType.TABLES, respBuilder.build()); } } } private static class ColumnsProvider extends MetadataRunnable { private static final Ordering COLUMNS_ORDERING = new Ordering() { @Override public int compare(ColumnMetadata left, ColumnMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .compare(left.getOrdinalPosition(), right.getOrdinalPosition()) .result(); } }; private final GetColumnsReq req; private ColumnsProvider(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetColumnsResp.Builder respBuilder = GetColumnsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, null, req.hasColumnNameFilter() ? req.getColumnNameFilter() : null ); try { final PojoRecordReader records = getPojoRecordReader(COLUMNS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Column c : records) { final ColumnMetadata.Builder columnBuilder = ColumnMetadata.newBuilder(); columnBuilder.setCatalogName(c.TABLE_CATALOG); columnBuilder.setSchemaName(c.TABLE_SCHEMA); columnBuilder.setTableName(c.TABLE_NAME); columnBuilder.setColumnName(c.COLUMN_NAME); columnBuilder.setOrdinalPosition(c.ORDINAL_POSITION); if (c.COLUMN_DEFAULT != null) { columnBuilder.setDefaultValue(c.COLUMN_DEFAULT); } if ("YES".equalsIgnoreCase(c.IS_NULLABLE)) { columnBuilder.setIsNullable(true); } else { columnBuilder.setIsNullable(false); } columnBuilder.setDataType(c.DATA_TYPE); if (c.CHARACTER_MAXIMUM_LENGTH != null) { columnBuilder.setCharMaxLength(c.CHARACTER_MAXIMUM_LENGTH); } if (c.CHARACTER_OCTET_LENGTH != null) { columnBuilder.setCharOctetLength(c.CHARACTER_OCTET_LENGTH); } if (c.NUMERIC_SCALE != null) { columnBuilder.setNumericScale(c.NUMERIC_SCALE); } if (c.NUMERIC_PRECISION != null) { columnBuilder.setNumericPrecision(c.NUMERIC_PRECISION); } if (c.NUMERIC_PRECISION_RADIX != null) { columnBuilder.setNumericPrecisionRadix(c.NUMERIC_PRECISION_RADIX); } if (c.DATETIME_PRECISION != null) { columnBuilder.setDateTimePrecision(c.DATETIME_PRECISION); } if (c.INTERVAL_TYPE != null) { columnBuilder.setIntervalType(c.INTERVAL_TYPE); } if (c.INTERVAL_PRECISION != null) { columnBuilder.setIntervalPrecision(c.INTERVAL_PRECISION); } if (c.COLUMN_SIZE != null) { columnBuilder.setColumnSize(c.COLUMN_SIZE); } metadata.add(columnBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, COLUMNS_ORDERING); respBuilder.addAllColumns(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get columns", e)); } finally { return new Response(RpcType.COLUMNS, respBuilder.build()); } } } /** * Helper method to create a {@link InfoSchemaFilter} that combines the given filters with an AND. * * @param catalogNameFilter Optional filter on catalog name * @param schemaNameFilter Optional filter on schema name * @param tableNameFilter Optional filter on table name * @param tableTypeFilter Optional filter on table type * @param columnNameFilter Optional filter on column name * @return information schema filter */ private static InfoSchemaFilter createInfoSchemaFilter(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, List tableTypeFilter, LikeFilter columnNameFilter) { FunctionExprNode exprNode = createLikeFunctionExprNode(CATS_COL_CATALOG_NAME, catalogNameFilter); // schema names are case insensitive in Drill and stored in lower case // convert like filter condition elements to lower case if (schemaNameFilter != null) { LikeFilter.Builder builder = LikeFilter.newBuilder(); if (schemaNameFilter.hasPattern()) { builder.setPattern(schemaNameFilter.getPattern().toLowerCase()); } if (schemaNameFilter.hasEscape()) { builder.setEscape(schemaNameFilter.getEscape().toLowerCase()); } schemaNameFilter = builder.build(); } exprNode = combineFunctions(AND_FUNCTION, exprNode, combineFunctions(OR_FUNCTION, createLikeFunctionExprNode(SHRD_COL_TABLE_SCHEMA, schemaNameFilter), createLikeFunctionExprNode(SCHS_COL_SCHEMA_NAME, schemaNameFilter) ) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(SHRD_COL_TABLE_NAME, tableNameFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createInFunctionExprNode(TBLS_COL_TABLE_TYPE, tableTypeFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(COLS_COL_COLUMN_NAME, columnNameFilter) ); return exprNode != null ? new InfoSchemaFilter(exprNode) : null; } /** * Helper method to create {@link FunctionExprNode} from {@link LikeFilter}. * @param fieldName Name of the filed on which the like expression is applied. * @param likeFilter * @return {@link FunctionExprNode} for given arguments. Null if the likeFilter is null. */ private static FunctionExprNode createLikeFunctionExprNode(String fieldName, LikeFilter likeFilter) { if (likeFilter == null) { return null; } return new FunctionExprNode(LIKE_FUNCTION, likeFilter.hasEscape() ? ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern()), new ConstantExprNode(likeFilter.getEscape())) : ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern())) ); } /** * Helper method to create {@link FunctionExprNode} from {@code List}. * @param fieldName Name of the filed on which the like expression is applied. * @param valuesFilter a list of values * @return {@link FunctionExprNode} for given arguments. Null if the valuesFilter is null. */ private static FunctionExprNode createInFunctionExprNode(String fieldName, List valuesFilter) { if (valuesFilter == null) { return null; } ImmutableList.Builder nodes = ImmutableList.builder(); nodes.add(new FieldExprNode(fieldName)); for(String type: valuesFilter) { nodes.add(new ConstantExprNode(type)); } return new FunctionExprNode(IN_FUNCTION, nodes.build()); } /** * Helper method to combine two {@link FunctionExprNode}s with a given functionName. If one of them is * null, other one is returned as it is. */ private static FunctionExprNode combineFunctions(final String functionName, final FunctionExprNode func1, final FunctionExprNode func2) { if (func1 == null) { return func2; } if (func2 == null) { return func1; } return new FunctionExprNode(functionName, ImmutableList.of(func1, func2)); } /** * Helper method to create a {@link PojoRecordReader} for given arguments. * @param tableType * @param filter * @param provider * @param userSession * @return */ private static PojoRecordReader getPojoRecordReader(final InfoSchemaTableType tableType, final InfoSchemaFilter filter, final DrillConfig config, final SchemaTreeProvider provider, final UserSession userSession) { final SchemaPlus rootSchema = provider.createFullRootSchema(userSession.getCredentials().getUserName(), newSchemaConfigInfoProvider(config, userSession, provider)); return tableType.getRecordReader(rootSchema, filter, userSession.getOptions()); } /** * Helper method to create a {@link SchemaConfigInfoProvider} instance for metadata purposes. * @param session * @param schemaTreeProvider * @return */ private static SchemaConfigInfoProvider newSchemaConfigInfoProvider(final DrillConfig config, final UserSession session, final SchemaTreeProvider schemaTreeProvider) { return new SchemaConfigInfoProvider() { private final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(config, this); @Override public ViewExpansionContext getViewExpansionContext() { return viewExpansionContext; } @Override public SchemaPlus getRootSchema(String userName) { return schemaTreeProvider.createRootSchema(userName, this); } @Override public OptionValue getOption(String optionKey) { return session.getOptions().getOption(optionKey); } @Override public String getQueryUserName() { return session.getCredentials().getUserName(); } }; } /** * Helper method to create {@link DrillPBError} for client response message. * @param failedFunction Brief description of the failed function. * @param ex Exception thrown * @return */ static DrillPBError createPBError(final String failedFunction, final Throwable ex) { final String errorId = UUID.randomUUID().toString(); logger.error("Failed to {}. ErrorId: {}", failedFunction, errorId, ex); final DrillPBError.Builder builder = DrillPBError.newBuilder(); builder.setErrorType(ErrorType.SYSTEM); // Metadata requests shouldn't cause any user errors builder.setErrorId(errorId); if (ex.getMessage() != null) { builder.setMessage(ex.getMessage()); } builder.setException(ErrorHelper.getWrapper(ex)); return builder.build(); } } |
blob | data class | t | t | f | data class | blob | 0 | 3592 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/work/metadata/MetadataProvider.java/#L84-L621 | 1 | 349 | 3592 | minor |
| 583 | YES, I found bad smells. The bad smells are: 1. Feature envy 2. Long method 3. Data clumps 4. Duplicated code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | Feature envy2 Long method3 Data clumps4 Duplicated code | t | f | f | . Feature envy2. Long method3. Data clumps4. Duplicated code | data class | 0 | 5796 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 2 | 583 | 5796 | critical |
| 138 | {"response": "YES I found bad smells", "bad smells are:": ["1. Long method", "2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ImportsAwareClipboardAction extends TextEditorAction { public static class Factory implements IClipboardActionFactory { @Inject private MembersInjector injector; @Override public TextEditorAction create(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) { ImportsAwareClipboardAction action = new ImportsAwareClipboardAction(bundle, prefix, editor, operationCode); injector.injectMembers(action); return action; } } private static final XbaseClipboardTransfer TRANSFER_INSTANCE = new XbaseClipboardTransfer(); private final int operationCode; private ITextOperationTarget textOperationTarget; private @Inject ImportsUtil importsUtil; /** * Creates the action. * * @param bundle * the resource bundle * @param prefix * a prefix to be prepended to the various resource keys (described in ResourceAction * constructor), or null if none * @param editor * the text editor. May not be null. * @param operationCode * the operation code */ public ImportsAwareClipboardAction(ResourceBundle bundle, String prefix, ITextEditor editor, final int operationCode) { super(bundle, prefix, editor); this.operationCode = operationCode; if (operationCode == ITextOperationTarget.CUT) { setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); } else if (operationCode == ITextOperationTarget.COPY) { setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); } else if (operationCode == ITextOperationTarget.PASTE) { setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); } else { Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$ } update(); } protected void internalDoOperation() { if (operationCode == ITextOperationTarget.PASTE) { doPasteWithImportsOperation(); } else { doCutCopyWithImportsOperation(); } } private void doCutCopyWithImportsOperation() { try { final XbaseClipboardData cbData = createClipboardData(); if (cbData != null ) { ClipboardUtil.clipboardOperation(new Function() { @Override public Boolean apply(Clipboard clipboard) { Map payload = newLinkedHashMap(); payload.put(cbData, TRANSFER_INSTANCE); TextTransfer textTransfer = TextTransfer.getInstance(); String textData = (String) clipboard.getContents(textTransfer); if (textData == null || textData.isEmpty()) { // StyledText copied any data to ClipBoard return Boolean.FALSE; } payload.put(textData, textTransfer); RTFTransfer rtfTransfer = RTFTransfer.getInstance(); String rtfData = (String) clipboard.getContents(rtfTransfer); if (rtfData != null && !rtfData.isEmpty()) { payload.put(rtfData, rtfTransfer); } List datas = newArrayList(); List dataTypes = newArrayList(); for (Entry entry : payload.entrySet()) { datas.add(entry.getKey()); dataTypes.add(entry.getValue()); } try { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } return Boolean.FALSE; } } }); } } finally { textOperationTarget.doOperation(operationCode); } } private void doPasteWithImportsOperation() { XbaseClipboardData xbaseClipboardData = ClipboardUtil .clipboardOperation(new Function() { @Override public XbaseClipboardData apply(Clipboard input) { Object content = input.getContents(TRANSFER_INSTANCE); if (content instanceof XbaseClipboardData) { return (XbaseClipboardData) content; } return null; } }); JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent(); String textFromClipboard = ClipboardUtil.getTextFromClipboard(); XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor)); if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) { doPasteXbaseCode(xbaseClipboardData, addImports); } else if (javaImportsContent != null) { doPasteJavaCode(textFromClipboard, javaImportsContent, addImports); } else { textOperationTarget.doOperation(operationCode); } } /** * Should not add imports when pasting into a {@link XStringLiteral} or Comments (except of JavaDoc) * * @param document * - {@link IDocument} to work with * @param caretOffset * - current caret offset */ protected boolean shouldAddImports(IDocument document, int caretOffset) { if (caretOffset == 0) { return true; } String typeRight = IDocument.DEFAULT_CONTENT_TYPE; String typeLeft = IDocument.DEFAULT_CONTENT_TYPE; try { typeRight = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset, false); typeLeft = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset > 0 ? caretOffset - 1 : caretOffset, false); } catch (BadLocationException exception) { // Should not happen } if (COMMENT_PARTITION.equals(typeRight) || STRING_LITERAL_PARTITION.equals(typeRight) || SL_COMMENT_PARTITION.equals(typeRight) || "__rich_string".equals(typeRight)) { if (typeLeft.equals(typeRight)) return false; } return true; } private int caretOffset(final XtextEditor xtextEditor) { ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer(); int caretOffset = sourceViewer.getTextWidget().getCaretOffset(); if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; caretOffset = extension.widgetOffset2ModelOffset(caretOffset); } return caretOffset; } private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(), xbaseClipboardData.getExtensionImports(), getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(), new String[] {}, getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private boolean sameTarget(XbaseClipboardData xbaseClipboardData) { IEditorInput editorInput = getTextEditor().getEditorInput(); if (editorInput == null) { return false; } return xbaseClipboardData.getSourceIndentifier().equals(editorInput.toString()); } private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.readOnly(new IUnitOfWork() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple, Set, Set> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; } private IXtextDocument getXtextDocument() { XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); IXtextDocument document = xtextEditor.getDocument(); return document; } @Override public void update() { super.update(); if (isModifyOperation() && !canModifyEditor()) { setEnabled(false); return; } ITextEditor editor = getTextEditor(); if (textOperationTarget == null && editor != null) textOperationTarget = editor.getAdapter(ITextOperationTarget.class); boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode())); setEnabled(isEnabled); } private int getOperationCode() { return operationCode; } @Override public void run() { if (textOperationTarget == null) return; ITextEditor editor = getTextEditor(); if (editor == null) return; if (isModifyOperation() && !validateEditorInputState()) return; BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { internalDoOperation(); } }); } private boolean isModifyOperation() { return operationCode != ITextOperationTarget.COPY; } private Shell getShell() { ITextEditor editor = getTextEditor(); if (editor != null) { IWorkbenchPartSite site = editor.getSite(); Shell shell = site.getShell(); if (shell != null && !shell.isDisposed()) { return shell; } } return null; } private Display getDisplay() { Shell shell = getShell(); if (shell != null) { return shell.getDisplay(); } return null; } @Override public void setEditor(ITextEditor editor) { super.setEditor(editor); this.textOperationTarget = null; } public static final class XbaseClipboardData { private String sourceIndentifier; private String[] imports; private String[] staticImports; private String[] extensionImports; public XbaseClipboardData(String sourceIndentifier, String[] imports, String[] staticImports, String[] extensionImports) { this.sourceIndentifier = sourceIndentifier; this.imports = imports; this.staticImports = staticImports; this.extensionImports = extensionImports; } public XbaseClipboardData(byte[] bytes) throws IOException { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes)); try { sourceIndentifier = dataIn.readUTF(); imports = readArray(dataIn); staticImports = readArray(dataIn); extensionImports = readArray(dataIn); } finally { dataIn.close(); } } protected final String[] readArray(DataInputStream dataIn) throws IOException { int count = dataIn.readInt(); String[] array = new String[count]; for (int i = 0; i < count; i++) { array[i] = dataIn.readUTF(); } return array; } public byte[] serialize() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); try { dataOut.writeUTF(sourceIndentifier); writeArray(dataOut, imports); writeArray(dataOut, staticImports); writeArray(dataOut, extensionImports); } finally { dataOut.close(); out.close(); } return out.toByteArray(); } protected final void writeArray(DataOutputStream dataOut, String[] array) throws IOException { dataOut.writeInt(array.length); for (int i = 0; i < array.length; i++) { dataOut.writeUTF(array[i]); } } public String getSourceIndentifier() { return sourceIndentifier; } public String[] getImports() { return imports; } public String[] getStaticImports() { return staticImports; } public String[] getExtensionImports() { return extensionImports; } } private static class XbaseClipboardTransfer extends ByteArrayTransfer { private static final String TYPE_NAME = "xbase-source-with-imports-transfer-format"; private static final int TYPEID = registerType(TYPE_NAME); @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object data, TransferData transferData) { if (data instanceof XbaseClipboardData) { try { super.javaToNative(((XbaseClipboardData) data).serialize(), transferData); } catch (IOException e) { //it's best to send nothing if there were problems } } } @Override protected Object nativeToJava(TransferData transferData) { byte[] bytes = (byte[]) super.nativeToJava(transferData); if (bytes != null) { try { return new XbaseClipboardData(bytes); } catch (IOException e) { } } return null; } } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1747 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xbase.ui/src/org/eclipse/xtext/xbase/ui/editor/actions/ImportsAwareClipboardAction.java/#L79-L520 | 2 | 138 | 1747 | minor |
| 2223 | { "message": "YES I found bad smells", "the bad smells are": ["Static method", "Long method", "Feature envy", "Duplicate code"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | static method, long method, feature envy, duplicate code | t | t | f | static method, long method, feature envy, duplicate code | blob | 0 | 13567 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 2 | 2223 | 13567 | major |
| 1772 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11921 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 2 | 1772 | 11921 | minor |
| 1105 | {"response":"YES I found bad smells","bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 9857 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 2 | 1105 | 9857 | minor |
| 1073 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 9620 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 1 | 1073 | 9620 | minor |
| 1393 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 10847 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 | 1 | 1393 | 10847 | minor |
| 142 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | long method | t | t | f | long method | data class | 0 | 1777 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 1 | 142 | 1777 | minor |
| 3891 | YES I found bad smells.The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 30, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Thread) public static class DeleteTasksBenchmark { private StateManager manager; private Storage storage; private Set taskIds; @Param({"1000", "10000", "50000"}) private int numTasksToDelete; @Setup(Level.Trial) public void setUpStorage() { Injector injector = getInjector(); manager = injector.getInstance(StateManager.class); storage = injector.getInstance(Storage.class); storage.prepare(); } // JMH warns heavily against using `Invocation` but this test seems to meet the requirements // of using it. Each benchmark will take more than one ms and it avoids awkward logic to // setup storage before the benchmark. @Setup(Level.Invocation) public void setUp() { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(Storage.MutableStoreProvider storeProvider) throws RuntimeException { taskIds = bulkInsertTasks(numTasksToDelete, storeProvider.getUnsafeTaskStore()); } }); } @Benchmark public Set run() { return storage.write((Storage.MutateWork.Quiet>) storeProvider -> { manager.deleteTasks(storeProvider, taskIds); return taskIds; }); } } |
blob | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | blob | 0 | 10181 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/jmh/java/org/apache/aurora/benchmark/StateManagerBenchmarks.java/#L117-L159 | 2 | 3891 | 10181 | major |
| 219 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PTransformReplacements { /** * Gets the singleton input of an {@link AppliedPTransform}, ignoring any additional inputs * returned by {@link PTransform#getAdditionalInputs()}. */ public static PCollection getSingletonMainInput( AppliedPTransform, ?, ?> application) { return getSingletonMainInput( application.getInputs(), application.getTransform().getAdditionalInputs().keySet()); } private static PCollection getSingletonMainInput( Map, PValue> inputs, Set> ignoredTags) { PCollection mainInput = null; for (Map.Entry, PValue> input : inputs.entrySet()) { if (!ignoredTags.contains(input.getKey())) { checkArgument( mainInput == null, "Got multiple inputs that are not additional inputs for a " + "singleton main input: %s and %s", mainInput, input.getValue()); checkArgument( input.getValue() instanceof PCollection, "Unexpected input type %s", input.getValue().getClass()); mainInput = (PCollection) input.getValue(); } } checkArgument( mainInput != null, "No main input found in inputs: Inputs %s, Side Input tags %s", inputs, ignoredTags); return mainInput; } public static PCollection getSingletonMainOutput( AppliedPTransform, ? extends PTransform>> transform) { return (PCollection) Iterables.getOnlyElement(transform.getOutputs().values()); } } |
blob | 1: data class, 2: long method | t | t | f | 1: data class, 2: long method | blob | 0 | 2390 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformReplacements.java/#L32-L73 | 1 | 219 | 2390 | minor |
| 403 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } } |
data class | Magic numbers2 Long method3 Feature envy | t | f | f | . Magic numbers2. Long method3. Feature envy | data class | 0 | 4118 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 | 2 | 403 | 4118 | major |
| 2204 | { "response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13510 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 1 | 2204 | 13510 | minor |
| 1463 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11027 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 1463 | 11027 | major |
| 2000 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataProvider { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MetadataProvider.class); private static final String IN_FUNCTION = "in"; private static final String LIKE_FUNCTION = "like"; private static final String AND_FUNCTION = "booleanand"; private static final String OR_FUNCTION = "booleanor"; /** * @return Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ public static Runnable catalogs(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { return new CatalogsProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the schema metadata for given {@link GetSchemasReq} and sends response at the end. */ public static Runnable schemas(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { return new SchemasProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the table metadata for given {@link GetTablesReq} and sends response at the end. */ public static Runnable tables(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { return new TablesProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the column metadata for given {@link GetColumnsReq} and sends response at the end. */ public static Runnable columns(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { return new ColumnsProvider(session, dContext, req, responseSender); } /** * Super class for all metadata provider runnable classes. */ private abstract static class MetadataRunnable implements Runnable { protected final UserSession session; private final ResponseSender responseSender; private final DrillbitContext dContext; private MetadataRunnable(final UserSession session, final DrillbitContext dContext, final ResponseSender responseSender) { this.session = Preconditions.checkNotNull(session); this.dContext = Preconditions.checkNotNull(dContext); this.responseSender = Preconditions.checkNotNull(responseSender); } @Override public void run() { try(SchemaTreeProvider schemaTreeProvider = new SchemaTreeProvider(dContext)) { responseSender.send(runInternal(session, schemaTreeProvider)); } catch (final Throwable error) { logger.error("Unhandled metadata provider error", error); } } /** * @return A {@link Response} message. Response must be returned in any case. */ protected abstract Response runInternal(UserSession session, SchemaTreeProvider schemaProvider); public DrillConfig getConfig() { return dContext.getConfig(); } } /** * Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ private static class CatalogsProvider extends MetadataRunnable { private static final Ordering CATALOGS_ORDERING = new Ordering() { @Override public int compare(CatalogMetadata left, CatalogMetadata right) { return Ordering.natural().compare(left.getCatalogName(), right.getCatalogName()); } }; private final GetCatalogsReq req; public CatalogsProvider(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetCatalogsResp.Builder respBuilder = GetCatalogsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(CATALOGS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Catalog c : records) { final CatalogMetadata.Builder catBuilder = CatalogMetadata.newBuilder(); catBuilder.setCatalogName(c.CATALOG_NAME); catBuilder.setDescription(c.CATALOG_DESCRIPTION); catBuilder.setConnect(c.CATALOG_CONNECT); metadata.add(catBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, CATALOGS_ORDERING); respBuilder.addAllCatalogs(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get catalogs", e)); } finally { return new Response(RpcType.CATALOGS, respBuilder.build()); } } } private static class SchemasProvider extends MetadataRunnable { private static final Ordering SCHEMAS_ORDERING = new Ordering() { @Override public int compare(SchemaMetadata left, SchemaMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .result(); }; }; private final GetSchemasReq req; private SchemasProvider(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetSchemasResp.Builder respBuilder = GetSchemasResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(SCHEMATA, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Schema s : records) { final SchemaMetadata.Builder schemaBuilder = SchemaMetadata.newBuilder(); schemaBuilder.setCatalogName(s.CATALOG_NAME); schemaBuilder.setSchemaName(s.SCHEMA_NAME); schemaBuilder.setOwner(s.SCHEMA_OWNER); schemaBuilder.setType(s.TYPE); schemaBuilder.setMutable(s.IS_MUTABLE); metadata.add(schemaBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, SCHEMAS_ORDERING); respBuilder.addAllSchemas(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get schemas", e)); } finally { return new Response(RpcType.SCHEMAS, respBuilder.build()); } } } private static class TablesProvider extends MetadataRunnable { private static final Ordering TABLES_ORDERING = new Ordering() { @Override public int compare(TableMetadata left, TableMetadata right) { return ComparisonChain.start() .compare(left.getType(), right.getType()) .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .result(); } }; private final GetTablesReq req; private TablesProvider(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, req.getTableTypeFilterCount() != 0 ? req.getTableTypeFilterList() : null, null); try { final PojoRecordReader records = getPojoRecordReader(TABLES, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Table t : records) { final TableMetadata.Builder tableBuilder = TableMetadata.newBuilder(); tableBuilder.setCatalogName(t.TABLE_CATALOG); tableBuilder.setSchemaName(t.TABLE_SCHEMA); tableBuilder.setTableName(t.TABLE_NAME); tableBuilder.setType(t.TABLE_TYPE); metadata.add(tableBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, TABLES_ORDERING); respBuilder.addAllTables(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get tables", e)); } finally { return new Response(RpcType.TABLES, respBuilder.build()); } } } private static class ColumnsProvider extends MetadataRunnable { private static final Ordering COLUMNS_ORDERING = new Ordering() { @Override public int compare(ColumnMetadata left, ColumnMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .compare(left.getOrdinalPosition(), right.getOrdinalPosition()) .result(); } }; private final GetColumnsReq req; private ColumnsProvider(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetColumnsResp.Builder respBuilder = GetColumnsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, null, req.hasColumnNameFilter() ? req.getColumnNameFilter() : null ); try { final PojoRecordReader records = getPojoRecordReader(COLUMNS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Column c : records) { final ColumnMetadata.Builder columnBuilder = ColumnMetadata.newBuilder(); columnBuilder.setCatalogName(c.TABLE_CATALOG); columnBuilder.setSchemaName(c.TABLE_SCHEMA); columnBuilder.setTableName(c.TABLE_NAME); columnBuilder.setColumnName(c.COLUMN_NAME); columnBuilder.setOrdinalPosition(c.ORDINAL_POSITION); if (c.COLUMN_DEFAULT != null) { columnBuilder.setDefaultValue(c.COLUMN_DEFAULT); } if ("YES".equalsIgnoreCase(c.IS_NULLABLE)) { columnBuilder.setIsNullable(true); } else { columnBuilder.setIsNullable(false); } columnBuilder.setDataType(c.DATA_TYPE); if (c.CHARACTER_MAXIMUM_LENGTH != null) { columnBuilder.setCharMaxLength(c.CHARACTER_MAXIMUM_LENGTH); } if (c.CHARACTER_OCTET_LENGTH != null) { columnBuilder.setCharOctetLength(c.CHARACTER_OCTET_LENGTH); } if (c.NUMERIC_SCALE != null) { columnBuilder.setNumericScale(c.NUMERIC_SCALE); } if (c.NUMERIC_PRECISION != null) { columnBuilder.setNumericPrecision(c.NUMERIC_PRECISION); } if (c.NUMERIC_PRECISION_RADIX != null) { columnBuilder.setNumericPrecisionRadix(c.NUMERIC_PRECISION_RADIX); } if (c.DATETIME_PRECISION != null) { columnBuilder.setDateTimePrecision(c.DATETIME_PRECISION); } if (c.INTERVAL_TYPE != null) { columnBuilder.setIntervalType(c.INTERVAL_TYPE); } if (c.INTERVAL_PRECISION != null) { columnBuilder.setIntervalPrecision(c.INTERVAL_PRECISION); } if (c.COLUMN_SIZE != null) { columnBuilder.setColumnSize(c.COLUMN_SIZE); } metadata.add(columnBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, COLUMNS_ORDERING); respBuilder.addAllColumns(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get columns", e)); } finally { return new Response(RpcType.COLUMNS, respBuilder.build()); } } } /** * Helper method to create a {@link InfoSchemaFilter} that combines the given filters with an AND. * * @param catalogNameFilter Optional filter on catalog name * @param schemaNameFilter Optional filter on schema name * @param tableNameFilter Optional filter on table name * @param tableTypeFilter Optional filter on table type * @param columnNameFilter Optional filter on column name * @return information schema filter */ private static InfoSchemaFilter createInfoSchemaFilter(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, List tableTypeFilter, LikeFilter columnNameFilter) { FunctionExprNode exprNode = createLikeFunctionExprNode(CATS_COL_CATALOG_NAME, catalogNameFilter); // schema names are case insensitive in Drill and stored in lower case // convert like filter condition elements to lower case if (schemaNameFilter != null) { LikeFilter.Builder builder = LikeFilter.newBuilder(); if (schemaNameFilter.hasPattern()) { builder.setPattern(schemaNameFilter.getPattern().toLowerCase()); } if (schemaNameFilter.hasEscape()) { builder.setEscape(schemaNameFilter.getEscape().toLowerCase()); } schemaNameFilter = builder.build(); } exprNode = combineFunctions(AND_FUNCTION, exprNode, combineFunctions(OR_FUNCTION, createLikeFunctionExprNode(SHRD_COL_TABLE_SCHEMA, schemaNameFilter), createLikeFunctionExprNode(SCHS_COL_SCHEMA_NAME, schemaNameFilter) ) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(SHRD_COL_TABLE_NAME, tableNameFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createInFunctionExprNode(TBLS_COL_TABLE_TYPE, tableTypeFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(COLS_COL_COLUMN_NAME, columnNameFilter) ); return exprNode != null ? new InfoSchemaFilter(exprNode) : null; } /** * Helper method to create {@link FunctionExprNode} from {@link LikeFilter}. * @param fieldName Name of the filed on which the like expression is applied. * @param likeFilter * @return {@link FunctionExprNode} for given arguments. Null if the likeFilter is null. */ private static FunctionExprNode createLikeFunctionExprNode(String fieldName, LikeFilter likeFilter) { if (likeFilter == null) { return null; } return new FunctionExprNode(LIKE_FUNCTION, likeFilter.hasEscape() ? ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern()), new ConstantExprNode(likeFilter.getEscape())) : ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern())) ); } /** * Helper method to create {@link FunctionExprNode} from {@code List}. * @param fieldName Name of the filed on which the like expression is applied. * @param valuesFilter a list of values * @return {@link FunctionExprNode} for given arguments. Null if the valuesFilter is null. */ private static FunctionExprNode createInFunctionExprNode(String fieldName, List valuesFilter) { if (valuesFilter == null) { return null; } ImmutableList.Builder nodes = ImmutableList.builder(); nodes.add(new FieldExprNode(fieldName)); for(String type: valuesFilter) { nodes.add(new ConstantExprNode(type)); } return new FunctionExprNode(IN_FUNCTION, nodes.build()); } /** * Helper method to combine two {@link FunctionExprNode}s with a given functionName. If one of them is * null, other one is returned as it is. */ private static FunctionExprNode combineFunctions(final String functionName, final FunctionExprNode func1, final FunctionExprNode func2) { if (func1 == null) { return func2; } if (func2 == null) { return func1; } return new FunctionExprNode(functionName, ImmutableList.of(func1, func2)); } /** * Helper method to create a {@link PojoRecordReader} for given arguments. * @param tableType * @param filter * @param provider * @param userSession * @return */ private static PojoRecordReader getPojoRecordReader(final InfoSchemaTableType tableType, final InfoSchemaFilter filter, final DrillConfig config, final SchemaTreeProvider provider, final UserSession userSession) { final SchemaPlus rootSchema = provider.createFullRootSchema(userSession.getCredentials().getUserName(), newSchemaConfigInfoProvider(config, userSession, provider)); return tableType.getRecordReader(rootSchema, filter, userSession.getOptions()); } /** * Helper method to create a {@link SchemaConfigInfoProvider} instance for metadata purposes. * @param session * @param schemaTreeProvider * @return */ private static SchemaConfigInfoProvider newSchemaConfigInfoProvider(final DrillConfig config, final UserSession session, final SchemaTreeProvider schemaTreeProvider) { return new SchemaConfigInfoProvider() { private final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(config, this); @Override public ViewExpansionContext getViewExpansionContext() { return viewExpansionContext; } @Override public SchemaPlus getRootSchema(String userName) { return schemaTreeProvider.createRootSchema(userName, this); } @Override public OptionValue getOption(String optionKey) { return session.getOptions().getOption(optionKey); } @Override public String getQueryUserName() { return session.getCredentials().getUserName(); } }; } /** * Helper method to create {@link DrillPBError} for client response message. * @param failedFunction Brief description of the failed function. * @param ex Exception thrown * @return */ static DrillPBError createPBError(final String failedFunction, final Throwable ex) { final String errorId = UUID.randomUUID().toString(); logger.error("Failed to {}. ErrorId: {}", failedFunction, errorId, ex); final DrillPBError.Builder builder = DrillPBError.newBuilder(); builder.setErrorType(ErrorType.SYSTEM); // Metadata requests shouldn't cause any user errors builder.setErrorId(errorId); if (ex.getMessage() != null) { builder.setMessage(ex.getMessage()); } builder.setException(ErrorHelper.getWrapper(ex)); return builder.build(); } } |
blob | long method | t | t | f | long method | blob | 0 | 12709 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/work/metadata/MetadataProvider.java/#L84-L621 | 1 | 2000 | 12709 | critical |
| 2482 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Inappropriate naming conventions, 5. Lack of modularity, 6. Poor code organization, 7. Lack of comments/documentation, 8. Complexity, 9. Lack of error handling, 10. Use of magic numbers, 11. Lack of proper testing, 12. Lack of proper design patterns and principles. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | Long method,2 Feature envy, 3 Duplicate code,4 Inappropriate naming conventions,5 Lack of modularity,6 Poor code organization,7 Lack of comments/documentation,8 Complexity,9 Lack of error handling, | t | f | f | . Long method, 2. Feature envy, 3. Duplicate code, 4. Inappropriate naming conventions, 5. Lack of modularity, 6. Poor code organization, 7. Lack of comments/documentation, 8. Complexity, 9. Lack of error handling, | blob | 0 | 14601 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 2 | 2482 | 14601 | minor |
| 788 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 7512 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 1 | 788 | 7512 | minor |
| 2337 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 14166 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 2337 | 14166 | minor |
| 1327 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | long method | t | t | f | long method | data class | 0 | 10704 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 1 | 1327 | 10704 | major |
| 300 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent Naming 5. High complexity 6. Useless comments 7. Large class 8. Primitive obsession 9. Inadequate logging 10. Nested conditionals 11. Inappropriate mixing of responsibilities | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | Long method2 Feature envy3 Duplicated code 4 Inconsistent Naming5 High complexity6 Useless comments7 Large class8 Primitive obsession9 Inadequate logging | t | f | f | . Long method2. Feature envy3. Duplicated code 4. Inconsistent Naming5. High complexity6. Useless comments7. Large class8. Primitive obsession9. Inadequate logging | blob | 0 | 3154 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 300 | 3154 | critical |
| 92 | {"response": "YES I found bad smells", "bad smells are": "1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @NbBundle.Messages({ "LocksFeatureUI_show=View by:", "LocksFeatureUI_aggregationByThreads=Threads", "LocksFeatureUI_aggregationByMonitors=Monitors", "LocksFeatureUI_aggregationHint=Results aggregation" }) abstract class LocksFeatureUI extends FeatureUI { private ProfilerToolbar toolbar; private LockContentionPanel locksView; // --- External implementation --------------------------------------------- abstract ProfilerClient getProfilerClient(); abstract void refreshResults(); // --- API implementation -------------------------------------------------- ProfilerToolbar getToolbar() { if (toolbar == null) initUI(); return toolbar; } JPanel getResultsUI() { if (locksView == null) initUI(); return locksView; } void sessionStateChanged(int sessionState) { refreshToolbar(sessionState); if (sessionState == Profiler.PROFILING_INACTIVE || sessionState == Profiler.PROFILING_IN_TRANSITION) { if (locksView != null) locksView.profilingSessionFinished(); } else if (sessionState == Profiler.PROFILING_RUNNING) { if (locksView != null) locksView.profilingSessionStarted(); } } void resetPause() { // if (lrPauseButton != null) lrPauseButton.setSelected(false); } void setForceRefresh() { if (locksView != null) locksView.setForceRefresh(true); } void refreshData() throws ClientUtils.TargetAppOrVMTerminated { if (locksView != null) locksView.refreshData(); } void resetData() { if (locksView != null) locksView.resetData(); } // --- UI ------------------------------------------------------------------ private JLabel shLabel; private ActionPopupButton shAggregation; private void initUI() { assert SwingUtilities.isEventDispatchThread(); // --- Results --------------------------------------------------------- locksView = new LockContentionPanel() { protected ProfilerClient getProfilerClient() { return LocksFeatureUI.this.getProfilerClient(); } }; locksView.lockContentionEnabled(); locksView.putClientProperty("HelpCtx.Key", "ProfileLocks.HelpCtx"); // NOI18N // --- Toolbar --------------------------------------------------------- shLabel = new GrayLabel(Bundle.LocksFeatureUI_show()); Action aThreads = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByThreads()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_THREADS); } }; Action aMonitors = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByMonitors()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_MONITORS); } }; shAggregation = new ActionPopupButton(aThreads, aMonitors); shAggregation.setToolTipText(Bundle.LocksFeatureUI_aggregationHint()); toolbar = ProfilerToolbar.create(true); toolbar.addSpace(2); toolbar.addSeparator(); toolbar.addSpace(5); toolbar.add(shLabel); toolbar.addSpace(2); toolbar.add(shAggregation); // --- Sync UI --------------------------------------------------------- setAggregation(LockContentionPanel.Aggregation.BY_THREADS); sessionStateChanged(getSessionState()); } private void refreshToolbar(final int state) { // if (toolbar != null) SwingUtilities.invokeLater(new Runnable() { // public void run() { // } // }); } private void setAggregation(LockContentionPanel.Aggregation aggregation) { locksView.setAggregation(aggregation); shAggregation.selectAction(aggregation.ordinal()); } } |
blob | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | blob | 0 | 1248 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler/src/org/graalvm/visualvm/lib/profiler/v2/features/LocksFeatureUI.java/#L65-L192 | 2 | 92 | 1248 | minor |
| 2408 | {"response":"YES I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 14390 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 2408 | 14390 | critical |
| 1750 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } } |
data class | t | f | f | data class | 0 | 11858 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 | 1 | 1750 | 11858 | minor | ||
| 1940 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
blob | data class | t | t | f | data class | blob | 0 | 12484 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 1940 | 12484 | minor |
| 2565 | YES, I found bad smells the bad smells are: 1. No meaningful class name (ExtendedCompletionList) 2. Boolean flag variable (inComplete) 3. Inconsistent indentation 4. Unclear or missing comments 5. No encapsulation of data fields (public access modifiers and direct access to data fields) 6. Lack of constructor overloading (default constructor is unnecessary) 7. Use of raw List type without specifying the type of elements allowed 8. Unused constructor parameter (inComplete) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | No meaningful class name (ExtendedCompletionList)2 Boolean flag variable (inComplete)3 Inconsistent indentation 4 Unclear or missing comments 5 No encapsulation of data fields (public access modifiers and direct access to data fields) 6 Lack of constructor overloading (default constructor is unnecessary) 7 Use of raw List type without specifying the type of elements allowed 8 Unused constructor parameter (inComplete) | t | f | f | . No meaningful class name (ExtendedCompletionList)2. Boolean flag variable (inComplete)3. Inconsistent indentation 4. Unclear or missing comments 5. No encapsulation of data fields (public access modifiers and direct access to data fields) 6. Lack of constructor overloading (default constructor is unnecessary) 7. Use of raw List type without specifying the type of elements allowed 8. Unused constructor parameter (inComplete) | data class | 0 | 14856 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 2 | 2565 | 14856 | major |
| 1387 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10837 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1387 | 10837 | major |
| 610 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 6126 | https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 | 1 | 610 | 6126 | minor |
| 1169 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | long method, blob | t | t | f | long method, blob | feature envy | 0 | 10192 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1169 | 10192 | major |
| 311 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getTraceback() { return traceback; } |
feature envy | blob | t | t | f | blob | feature envy | 0 | 3207 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-jupyter/src/main/java/org/apache/zeppelin/jupyter/nbformat/Error.java/#L48-L50 | 1 | 311 | 3207 | critical |
| 114 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Magic number" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | long method, magic number | t | t | f | long method, magic number | data class | 0 | 1489 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 2 | 114 | 1489 | critical |
| 2331 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
blob | long method | t | t | f | long method | blob | 0 | 14153 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 2331 | 14153 | minor |
| 758 | { "message": "YES I found bad smells", "bad_smells_are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
blob | data class | t | t | f | data class | blob | 0 | 7065 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 1 | 758 | 7065 | minor |
| 163 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorTestCaseFinder { private static final Logger log = LoggerFactory.getLogger(IteratorTestCaseFinder.class); /** * Instantiates all test cases provided. * * @return A list of {@link IteratorTestCase}s. */ public static List findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet classes = cp .getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List testCases = new ArrayList<>(); // final Set> classes = // reflections.getSubTypesOf(IteratorTestCase.class); for (ClassInfo classInfo : classes) { Class clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1997 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/iterator-test-harness/src/main/java/org/apache/accumulo/iteratortest/IteratorTestCaseFinder.java/#L35-L81 | 1 | 163 | 1997 | minor |
| 339 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class LdapProtocolUtils { /** A delimiter for the replicaId */ public static final String COOKIE_DELIM = ","; /** the prefix for replicaId value */ public static final String REPLICA_ID_PREFIX = "rid="; public static final int REPLICA_ID_PREFIX_LEN = REPLICA_ID_PREFIX.length(); /** the prefix for Csn value */ public static final String CSN_PREFIX = "csn="; private static final int CSN_PREFIX_LEN = CSN_PREFIX.length(); private static final Logger LOG = LoggerFactory.getLogger( LdapProtocolUtils.class ); private LdapProtocolUtils() { } /** * Extracts request controls from a request to populate into an * OperationContext. * * @param opContext the context to populate with request controls * @param request the request to extract controls from */ public static void setRequestControls( OperationContext opContext, Request request ) { if ( request.getControls() != null ) { opContext .addRequestControls( request.getControls().values().toArray( LdapProtocolConstants.EMPTY_CONTROLS ) ); } } /** * Extracts response controls from a an OperationContext to populate into * a Response object. * * @param opContext the context to extract controls from * @param response the response to populate with response controls */ public static void setResponseControls( OperationContext opContext, Response response ) { response.addAllControls( opContext.getResponseControls() ); } public static byte[] createCookie( int replicaId, String csn ) { // the syncrepl cookie format (compatible with OpenLDAP) // rid=nn,csn=xxxz String replicaIdStr = StringUtils.leftPad( Integer.toString( replicaId ), 3, '0' ); return Strings.getBytesUtf8( REPLICA_ID_PREFIX + replicaIdStr + COOKIE_DELIM + CSN_PREFIX + csn ); } /** * Check the cookie syntax. A cookie must have the following syntax : * { rid={replicaId},csn={CSN} } * * @param cookieString The cookie * @return true if the cookie is valid */ public static boolean isValidCookie( String cookieString ) { if ( ( cookieString == null ) || ( cookieString.trim().length() == 0 ) ) { return false; } int pos = cookieString.indexOf( COOKIE_DELIM ); // position should start from REPLICA_ID_PREFIX_LEN or higher cause a cookie can be // like "rid=0,csn={csn}" or "rid=11,csn={csn}" if ( pos <= REPLICA_ID_PREFIX_LEN ) { return false; } String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, pos ); try { Integer.parseInt( replicaId ); } catch ( NumberFormatException e ) { LOG.debug( "Failed to parse the replica id {}", replicaId ); return false; } if ( pos == cookieString.length() ) { return false; } String csnString = cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); return Csn.isValid( csnString ); } /** * returns the CSN present in cookie * * @param cookieString the cookie * @return The CSN */ public static String getCsn( String cookieString ) { int pos = cookieString.indexOf( COOKIE_DELIM ); return cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); } /** * returns the replica id present in cookie * * @param cookieString the cookie * @return The replica Id */ public static int getReplicaId( String cookieString ) { String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, cookieString.indexOf( COOKIE_DELIM ) ); return Integer.parseInt( replicaId ); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 3490 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolUtils.java/#L38-L171 | 2 | 339 | 3490 | minor |
| 1158 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FontDelegate { private static int[] defaultMapping = { CONTROL_TEXT_FONT, SYSTEM_TEXT_FONT, USER_TEXT_FONT, CONTROL_TEXT_FONT, CONTROL_TEXT_FONT, SUB_TEXT_FONT }; FontUIResource[] fonts; // menu and window are mapped to controlFont public FontDelegate() { fonts = new FontUIResource[6]; } public FontUIResource getFont(int type) { int mappedType = defaultMapping[type]; if (fonts[type] == null) { Font f = getPrivilegedFont(mappedType); if (f == null) { f = new Font(getDefaultFontName(type), getDefaultFontStyle(type), getDefaultFontSize(type)); } fonts[type] = new FontUIResource(f); } return fonts[type]; } /** * This is the same as invoking * Font.getFont(key), with the exception * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } ); } } |
blob | long method | t | t | f | long method | blob | 0 | 10145 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java/#L357-L399 | 1 | 1158 | 10145 | minor |
| 1917 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 12409 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 2 | 1917 | 12409 | minor |
| 4095 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10789 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 2 | 4095 | 10789 | minor |
| 2116 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Controller public class SignupController { private final SignupHelper signupHelper; @Inject public SignupController(AccountRepository accountRepository, SignedUpGateway gateway) { this.signupHelper = new SignupHelper(accountRepository, gateway); } /** * Render a signup form to the person as HTML in their web browser. */ @RequestMapping(value="/signup", method=RequestMethod.GET) public SignupForm signupForm(WebRequest request) { Connection connection = ProviderSignInUtils.getConnection(request); if (connection != null) { request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Greenhouse account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST); return SignupForm.fromProviderUser(connection.fetchUserProfile()); } else { return new SignupForm(); } } /** * Process a signup form submission. * Delegate to a {@link SignupHelper} to actually complete the signin transaction. * Redirects the new member to the application home page on successful sign-in. */ @RequestMapping(value="/signup", method=RequestMethod.POST) public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) { if (formBinding.hasErrors()) { return null; } boolean result = signupHelper.signup(form, formBinding, new SignupCallback() { public void postSignup(Account account) { ProviderSignInUtils.handlePostSignUp(account.getId().toString(), request); } }); return result ? "redirect:/" : null; } @RequestMapping(value="/signup", method=RequestMethod.POST, consumes="application/json") public ResponseEntity> signupFromApi(@RequestBody SignupForm form) { BindingResult formBinding = validate(form); // Temporary manual validation until SPR-9826 is fixed. if (formBinding.hasErrors()) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Validation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } boolean result = signupHelper.signup(form, formBinding); if (result) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account created"); return new ResponseEntity>(errorResponse, HttpStatus.CREATED); } else { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account creation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } } private BindException validate(SignupForm form) { BindException errors; errors = new BindException(form, "signupForm"); LazyValidatorFactory lvf = new LazyValidatorFactory(); Validator validator = new SpringValidatorAdapter(lvf.getValidator()); ValidationUtils.invokeValidator(validator, form, errors); return errors; } private List> getErrorsMap(BindingResult formBinding) { List fieldErrors = formBinding.getFieldErrors(); List> errors = new ArrayList>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map fieldErrorMap = new HashMap(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap); } return errors; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13195 | https://github.com/spring-projects/greenhouse/blob/c7994183812150de971ef4a76c08d5b4631ab5d1/src/main/java/com/springsource/greenhouse/signup/SignupController.java/#L54-L143 | 1 | 2116 | 13195 | minor |
| 5153 | I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 14424 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L80311-L81098 | 2 | 5153 | 14424 | critical | ||
| 279 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Wrap extends DoFn> { @ProcessElement public void processElement(ProcessContext ctx) { ctx.output(KV.of(ctx.timestamp().getMillis(), ctx.element())); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 2988 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/euphoria/src/main/java/org/apache/beam/sdk/extensions/euphoria/core/translate/TimestampExtractTransform.java/#L78-L84 | 1 | 279 | 2988 | minor |
| 1093 | YES I found bad smells 1. Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain. 2. Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication. 3. Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy. 4. Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XelatexRunner extends LatexRunner { /** * Create a new ProgramRunner. */ public XelatexRunner() { super(); } protected String getWindowsProgramName() { return "xelatex.exe"; } protected String getUnixProgramName() { return "xelatex"; } public String getDescription() { return "XeLatex program"; } /** * Enable SyncTeX */ public String getDefaultArguments() { return "-synctex=1 "+super.getDefaultArguments(); } /** * @return output file format (pdf) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_PDF; } } |
data class | Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain2 Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication3 Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy4 Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner) | t | f | f | . Long method: The class XelatexRunner contains multiple methods, each with a different purpose, making it a long and potentially confusing class to maintain.2. Duplicate code: The methods getWindowsProgramName() and getUnixProgramName() have similar implementation, indicating possible code duplication.3. Feature envy: The method getOutputFormat() uses a constant from a different class, indicating a possible feature envy.4. Inappropriate naming: The class name XelatexRunner does not accurately represent its purpose, as it extends a more general class (LatexRunner). | data class | 0 | 9748 | https://github.com/eclipse/texlipse/blob/1bc72f856d4144ad0bc9baaa9575457bd7b68e1a/org.eclipse.texlipse/source/org/eclipse/texlipse/builder/XelatexRunner.java/#L20-L55 | 2 | 1093 | 9748 | critical |
| 2483 | YES I found bad smells the bad smells are: 1) Long method, 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeOrderer implements ILayoutPhase { /** intermediate processing configuration. */ private static final LayoutProcessorConfiguration INTERMEDIATE_PROCESSING_CONFIG = LayoutProcessorConfiguration.create() .before(TreeLayoutPhases.P2_NODE_ORDERING) .add(IntermediateProcessorStrategy.ROOT_PROC) .add(IntermediateProcessorStrategy.FAN_PROC); /** * {@inheritDoc} */ @Override public LayoutProcessorConfiguration getLayoutProcessorConfiguration(final TGraph graph) { return INTERMEDIATE_PROCESSING_CONFIG; } /** * {@inheritDoc} */ public void process(final TGraph tGraph, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange node", 1); // find the root of the component // expected only one root exists TNode root = null; LinkedList roots = new LinkedList(); Iterator it = tGraph.getNodes().iterator(); while (root == null && it.hasNext()) { TNode tNode = it.next(); if (tNode.getProperty(InternalProperties.ROOT)) { root = tNode; } } // order each level roots.add(root); orderLevel(roots, progressMonitor.subTask(1.0f)); progressMonitor.done(); } /** * Order each level by separating the nodes into leaves and inner nodes. And then fill gaps with * corresponding leaves. * * @param currentLevel * @param progressMonitor */ private void orderLevel(final LinkedList currentLevel, final IElkProgressMonitor progressMonitor) { progressMonitor.begin("Processor arrange level", 1); int pos = 0; // sort all nodes in this level by their fan out // so the leaves are at the end of the list Collections.sort(currentLevel, PropertyHolderComparator.with(InternalProperties.FAN)); // find the first occurence of a leave in the list int firstOcc = currentLevel.size(); ListIterator it = currentLevel.listIterator(currentLevel.size()); boolean notNull = true; while (notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { firstOcc--; } else { notNull = false; } } // seperate the level into leaves and inner nodes List tmp = currentLevel.subList(0, firstOcc); LinkedList inners = new LinkedList(tmp); tmp = currentLevel.subList(firstOcc, currentLevel.size()); LinkedList leaves = new LinkedList(tmp); // check if their are inner nodes left if (inners.isEmpty()) { // leave the leaves in their order for (TNode tENode : leaves) { tENode.setProperty(InternalProperties.POSITION, pos++); } } else { // order each level of descendants of the inner nodes int size = inners.size(); for (TNode tPNode : inners) { tPNode.setProperty(InternalProperties.POSITION, pos++); // set the position of the children and set them in order LinkedList children = tPNode.getChildrenCopy(); orderLevel(children, progressMonitor.subTask(1 / size)); // order the children by their reverse position Collections.sort(children, Collections.reverseOrder(PropertyHolderComparator.with(InternalProperties.POSITION))); // reset the list of children with the new order List sortedOutEdges = new LinkedList(); for (TNode tNode : children) { for (TEdge tEdge : tPNode.getOutgoingEdges()) { if (tEdge.getTarget() == tNode) { sortedOutEdges.add(tEdge); } } } tPNode.getOutgoingEdges().clear(); tPNode.getOutgoingEdges().addAll(sortedOutEdges); // fill gaps with leafs it = leaves.listIterator(leaves.size()); int fillGap = tPNode.getOutgoingEdges().size(); notNull = true; while ((0 < fillGap) && notNull && it.hasPrevious()) { TNode tNode = (TNode) it.previous(); if ((tNode.getProperty(InternalProperties.FAN) == 0)) { tNode.setProperty(InternalProperties.POSITION, pos++); fillGap--; it.remove(); } else { notNull = false; } } } } progressMonitor.done(); } } |
blob | ) Long method, 2) Feature envy | t | f | f | ) Long method, 2) Feature envy | blob | 0 | 14602 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.alg.mrtree/src/org/eclipse/elk/alg/mrtree/p2order/NodeOrderer.java/#L37-L169 | 2 | 2483 | 14602 | major |
| 2017 | as the code provided is incomplete. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12773 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 2 | 2017 | 12773 | major | ||
| 1529 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | long method | t | t | f | long method | blob | 0 | 11204 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 1 | 1529 | 11204 | major |
| 1277 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10590 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 1 | 1277 | 10590 | critical |
| 117 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 1507 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 2 | 117 | 1507 | minor |
| 250 | {"message": "YES I found bad smells", "bad smells are": ["1.Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | 1.long method | t | t | f | 1.long method | data class | 0 | 2685 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 2 | 250 | 2685 | major |
| 208 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FastRTrace { static final class Helper extends RBaseNode { @Child private GetFunctions.Get getNode; @Child private EnvFunctions.TopEnv topEnv; @Child private FrameFunctions.ParentFrame parentFrame; protected Object getWhere(VirtualFrame frame) { if (topEnv == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); topEnv = insert(TopEnvNodeGen.create()); } if (parentFrame == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); parentFrame = insert(ParentFrameNodeGen.create()); } return topEnv.execute(frame, parentFrame.execute(frame, 1), RNull.instance); } protected Object getFunction(VirtualFrame frame, Object what, Object where) { if (getNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); getNode = insert(GetNodeGen.create()); } return getNode.execute(frame, what, where, RType.Function.getName(), true); } protected void checkWhat(Object what) { if (what == RMissing.instance) { throw error(RError.Message.ARGUMENT_MISSING, "what"); } } protected RFunction checkFunction(Object what) { if (what instanceof RFunction) { RFunction func = (RFunction) what; if (func.isBuiltin()) { throw error(RError.Message.GENERIC, "builtin functions cannot be traced"); } else { return func; } } else { throw error(RError.Message.ARG_MUST_BE_CLOSURE); } } } @RBuiltin(name = ".fastr.trace", visibility = CUSTOM, kind = PRIMITIVE, parameterNames = {"what", "tracer", "exit", "at", "print", "signature", "where"}, behavior = COMPLEX) public abstract static class Trace extends RBuiltinNode.Arg7 { @Child private TraceFunctions.PrimTrace primTrace; @Child private CastLogicalNode castLogical; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @Child private Helper helper = new Helper(); static { Casts.noCasts(Trace.class); } @Specialization protected Object trace(VirtualFrame frame, Object whatObj, Object tracer, Object exit, Object at, Object printObj, Object signature, Object whereObj) { Object what = whatObj; helper.checkWhat(what); Object where = whereObj; if (where == RMissing.instance) { where = helper.getWhere(frame); } String funcName = RRuntime.asString(what); if (funcName != null) { what = helper.getFunction(frame, what, where); } RFunction func = helper.checkFunction(what); if (tracer == RMissing.instance && exit == RMissing.instance && at == RMissing.instance && printObj == RMissing.instance && signature == RMissing.instance) { // simple case, nargs() == 1, corresponds to .primTrace that has invisible output if (primTrace == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); primTrace = insert(PrimTraceNodeGen.create()); } Object result = primTrace.execute(frame, func); visibility.execute(frame, false); return result; } if (at != RMissing.instance) { throw RError.nyi(this, "'at'"); } boolean print = true; if (printObj != RMissing.instance) { if (castLogical == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castLogical = insert(CastLogicalNodeGen.create(false, false, false)); } print = RRuntime.fromLogical((byte) castLogical.doCast(printObj)); } complexCase(func, tracer, exit, at, print, signature); visibility.execute(frame, true); return Utils.toString(func); } @TruffleBoundary private void complexCase(RFunction func, Object tracerObj, @SuppressWarnings("unused") Object exit, Object at, boolean print, @SuppressWarnings("unused") Object signature) { // the complex case RPairList tracer; if (tracerObj instanceof RFunction) { Closure closure = Closure.createLanguageClosure(RASTUtils.createCall(tracerObj, false, ArgumentsSignature.empty(0)).asRNode()); tracer = RDataFactory.createLanguage(closure); } else if ((tracerObj instanceof RPairList && ((RPairList) tracerObj).isLanguage())) { tracer = (RPairList) tracerObj; } else { throw error(RError.Message.GENERIC, "tracer is unexpected type"); } TraceHandling.enableStatementTrace(func, tracer, at, print); } } @RBuiltin(name = ".fastr.untrace", visibility = OFF, kind = PRIMITIVE, parameterNames = {"what", "signature", "where"}, behavior = COMPLEX) public abstract static class Untrace extends RBuiltinNode.Arg3 { @Child private TraceFunctions.PrimUnTrace primUnTrace; @Child private Helper helper = new Helper(); static { Casts.noCasts(Untrace.class); } @Specialization protected Object untrace(VirtualFrame frame, Object whatObj, Object signature, Object whereObj) { Object what = whatObj; helper.checkWhat(what); Object where = whereObj; if (where == RMissing.instance) { where = helper.getWhere(frame); } String funcName = RRuntime.asString(what); if (funcName != null) { what = helper.getFunction(frame, what, where); } RFunction func = helper.checkFunction(what); if (signature == RMissing.instance) { if (primUnTrace == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); primUnTrace = insert(PrimUnTraceNodeGen.create()); } primUnTrace.execute(frame, func); } else { throw RError.nyi(this, "method tracing"); } return Utils.toString(func); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2310 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/fastr/FastRTrace.java/#L70-L223 | 2 | 208 | 2310 | critical |
| 1564 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 11320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 2 | 1564 | 11320 | minor |
| 147 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AttributeUtils { public static Attribute[] readAttributes(DataInputStream dataInputstream, ConstantPool cpool) { try { int length = dataInputstream.readUnsignedShort(); if (length == 0) { return Attribute.NoAttributes; } Attribute[] attrs = new Attribute[length]; for (int i = 0; i < length; i++) { attrs[i] = Attribute.readAttribute(dataInputstream, cpool); } return attrs; } catch (IOException e) { throw new ClassFormatException("IOException whilst reading set of attributes: " + e.toString()); } } /** Write (serialize) a set of attributes into a specified output stream */ public static void writeAttributes(Attribute[] attributes, DataOutputStream file) throws IOException { if (attributes == null) { file.writeShort(0); } else { file.writeShort(attributes.length); for (int i = 0; i < attributes.length; i++) { attributes[i].dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SIGNATURE) { return (Signature) attributes[i]; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_CODE) { return (Code) attributes[i]; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { return (ExceptionTable) attributes[i]; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { return (ConstantValue) attributes[i]; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { for (int i = 0; i < attributes.length; i++) { attributes[i].accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { return true; } } return false; } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { return (SourceFile) attributes[i]; } } return null; } } |
blob | long method | t | t | f | long method | blob | 0 | 1836 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java/#L9-L99 | 1 | 147 | 1836 | major |
| 2676 | YES, I found bad smells. The bad smells are: 1. Long Method, 2. Inappropriate Intimacy, 3. Large Class, 4. Duplicate Code, 5. Magic Numbers, 6. Conflicting Method, 7. Lazy Class. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
blob | Long Method, 2 Inappropriate Intimacy, 3 Large Class, 4 Duplicate Code, 5 Magic Numbers, 6 Conflicting Method, 7 Lazy Class | t | f | f | . Long Method, 2. Inappropriate Intimacy, 3. Large Class, 4. Duplicate Code, 5. Magic Numbers, 6. Conflicting Method, 7. Lazy Class. | blob | 0 | 15238 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 2676 | 15238 | minor |
| 395 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component("org.apache.usergrid.rest.management.organizations.applications.ApplicationResource") @Scope("prototype") @Produces({ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", "text/jscript" }) public class ApplicationResource extends AbstractContextResource { private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); public static final String CONFIRM_APPLICATION_IDENTIFIER = "confirm_application_identifier"; public static final String RESTORE_PASSWORD = "restore_password"; //@Autowired //protected ExportService exportService; OrganizationInfo organization; UUID applicationId; ApplicationInfo application; @Autowired private SignInProviderFactory signInProviderFactory; public ApplicationResource() { } public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { this.organization = organization; this.applicationId = applicationId; return this; } public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { this.organization = organization; applicationId = application.getId(); this.application = application; return this; } @RequireOrganizationAccess @GET @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getApplication( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); ServiceManager sm = smf.getServiceManager( applicationId ); response.setAction( "get" ); response.setApplication( sm.getApplication() ); response.setParams( ui.getQueryParameters() ); response.setResults( management.getApplicationMetadata( applicationId ) ); return response; } @RequireOrganizationAccess @GET @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get application client credentials"); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.getClientSecretForApplication( applicationId ) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @POST @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse generateCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "generate application client credentials" ); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.newClientSecretForApplication(applicationId) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @GET @JSONP @Path("_size") public ApiResponse getApplicationSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "get application size for all entities" ); long size = management.getApplicationSize(this.applicationId); Map map = new HashMap<>(); Map innerMap = new HashMap<>(); Map sumMap = new HashMap<>(); innerMap.put("application",size); sumMap.put("size",innerMap); map.put("aggregation", sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("{collection_name}/_size") public ApiResponse getCollectionSize( @Context UriInfo ui, @PathParam( "collection_name" ) String collection_name, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); long size = management.getCollectionSize(this.applicationId, collection_name); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); Map innerMap = new HashMap<>(); innerMap.put(collection_name,size); sumMap.put("size",innerMap); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("collections/_size") public ApiResponse getEachCollectionSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); Map sizes = management.getEachCollectionSize(this.applicationId); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); sumMap.put("size",sizes); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @POST @Path("sia-provider") @Consumes(APPLICATION_JSON) @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, Map json, @QueryParam("callback") @DefaultValue("") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "post signin provider configuration" ); Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); SignInAsProvider signInAsProvider = null; if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { signInAsProvider = signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { signInAsProvider = signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { signInAsProvider = signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); } Preconditions.checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); signInAsProvider.saveToConfiguration( json ); return response; } // @POST // @Path("export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // // UUID jobUUID = null; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( bucketName == null ) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // json.put("organizationId", organization.getUuid()); // json.put( "applicationId",applicationId); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // catch ( Exception e ) { // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // return Response.status( SC_INTERNAL_SERVER_ERROR ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // @POST // @Path("collection/{collection_name}/export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui, // @PathParam( "collection_name" ) String collection_name ,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // UUID jobUUID = null; // String colExport = collection_name; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // //checkJsonExportProperties(json); // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // if(bucketName == null) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // // json.put( "organizationId",organization.getUuid() ); // json.put( "applicationId", applicationId); // json.put( "collectionName", colExport); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ) // .build(); // } // catch ( Exception e ) { // // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // // OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_INTERNAL_SERVER_ERROR ) // .setErrorDescription( e.getMessage() ) // .buildJSONMessage(); // // return Response.status( errorMsg.getResponseStatus() ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ) // .build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // // @Path( "imports" ) // public ImportsResource importGetJson( @Context UriInfo ui, // @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) // throws Exception { // // // return getSubResource( ImportsResource.class ).init( organization, application ); // } @GET @Path("/status") public Response getStatus() { Map statusMap = new HashMap(); EntityManager em = emf.getEntityManager( applicationId ); if ( !emf.getIndexHealth().equals( Health.RED ) ) { statusMap.put("message", "Index Health Status RED for application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } try { if ( em.getApplication() == null ) { statusMap.put("message", "Application " + applicationId + " not found"); return Response.status( SC_NOT_FOUND ).entity( statusMap ).build(); } } catch (Exception ex) { statusMap.put("message", "Error looking up application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } return Response.status( SC_OK ).entity( null ).build(); } /** * Put on application URL will restore application if it was deleted. */ @PUT @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executePut( @Context UriInfo ui, String body, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if ( applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (!SubjectUtils.isServiceAdmin()) { // require password if it exists String storedRestorePassword = restorePasswordService.getApplicationRestorePassword(applicationId); if (StringUtils.isNotEmpty(storedRestorePassword)) { // must have matching password as query parameter String suppliedRestorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (!storedRestorePassword.equals(suppliedRestorePassword)) { throw new IllegalArgumentException("Application cannot be restored without application password"); } } } management.restoreApplication( applicationId ); // not deleting password -- will be changed upon successful soft delete ApiResponse response = createApiResponse(); response.setAction( "restore" ); response.setApplication( emf.getEntityManager( applicationId ).getApplication() ); response.setParams( ui.getQueryParameters() ); return response; } /** * Caller MUST pass confirm_application_identifier that is either the UUID or the * name of the application to be deleted. Yes, this is redundant and intended to * be a protection measure to force caller to confirm that they want to do a delete. */ @DELETE @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executeDelete( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback, @QueryParam(CONFIRM_APPLICATION_IDENTIFIER) String confirmApplicationIdentifier) throws Exception { if ( application == null && applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } // If the path uses name then expect name, otherwise if they use uuid then expect uuid. if (application == null) { if (!applicationId.toString().equals( confirmApplicationIdentifier )) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application id."); } } else if (!application.getName().split( "/" )[1].equals( confirmApplicationIdentifier ) ) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application name"); } String restorePassword = null; ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (SubjectUtils.isServiceAdmin()) { restorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (StringUtils.isNotEmpty(restorePassword)) { // save password, required for future undelete if not sysadmin restorePasswordService.setApplicationRestorePassword(applicationId, restorePassword); } } management.deleteApplication( applicationId ); if (restorePassword == null) { // clear restore password restorePasswordService.removeApplicationRestorePassword(applicationId); } if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() deleted appId = {}", applicationId); } ApiResponse response = createApiResponse(); response.setAction( "delete" ); response.setApplication(emf.getEntityManager( applicationId ).getApplication()); response.setParams(ui.getQueryParameters()); if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() sending response "); } return response; } private ApplicationRestorePasswordService getApplicationRestorePasswordService() { return injector.getInstance(ApplicationRestorePasswordService.class); } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 4028 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/rest/src/main/java/org/apache/usergrid/rest/management/organizations/applications/ApplicationResource.java/#L63-L563 | 2 | 395 | 4028 | major |
| 212 | {"message":"YES I found bad smells","bad_smells":["1. Long Method","2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 2323 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 | 1 | 212 | 2323 | minor |
| 601 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Overuse of inheritance 4. Lack of encapsulation 5. Inappropriate naming conventions 6. Excessive comments 7. Code repetition 8. Poor exception handling 9. Lack of modularity 10. High complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } } |
blob | Long method2 Feature envy3 Overuse of inheritance4 Lack of encapsulation5 Inappropriate naming conventions6 Excessive comments7 Code repetition8 Poor exception handling9 Lack of modularity | t | f | f | . Long method2. Feature envy3. Overuse of inheritance4. Lack of encapsulation5. Inappropriate naming conventions6. Excessive comments7. Code repetition8. Poor exception handling9. Lack of modularity | blob | 0 | 5994 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 | 2 | 601 | 5994 | minor |
| 1342 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10744 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 1 | 1342 | 10744 | minor |
| 2205 | YES, I found bad smells the bad smells are: 1. Long method 2. Inappropriate inheritance 3. Primitive obsession 4. Feature envy 5. Data class 6. Hashcode and equals not overridden in superclass | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
blob | Long method 2 Inappropriate inheritance 3 Primitive obsession 4 Feature envy 5 Data class 6 Hashcode and equals not overridden in superclass | t | f | f | . Long method 2. Inappropriate inheritance 3. Primitive obsession 4. Feature envy 5. Data class 6. Hashcode and equals not overridden in superclass | blob | 0 | 13511 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 2205 | 13511 | minor |
| 2086 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 13101 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 2 | 2086 | 13101 | major |
| 201 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IgnoreCommitOptimizeUpdateProcessorFactory extends UpdateRequestProcessorFactory { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String DEFAULT_RESPONSE_MSG = "Explicit commit/optimize requests are forbidden!"; protected ErrorCode errorCode; protected String responseMsg; protected boolean ignoreOptimizeOnly = false; // default behavior is to ignore commits and optimize @Override public void init(final NamedList args) { SolrParams params = (args != null) ? args.toSolrParams() : null; if (params == null) { errorCode = ErrorCode.FORBIDDEN; // default is 403 error responseMsg = DEFAULT_RESPONSE_MSG; ignoreOptimizeOnly = false; return; } ignoreOptimizeOnly = params.getBool("ignoreOptimizeOnly", false); int statusCode = params.getInt("statusCode", ErrorCode.FORBIDDEN.code); if (statusCode == 200) { errorCode = null; // not needed but makes the logic clearer responseMsg = params.get("responseMessage"); // OK to be null for 200's } else { errorCode = ErrorCode.getErrorCode(statusCode); if (errorCode == ErrorCode.UNKNOWN) { // only allow the error codes supported by the SolrException.ErrorCode class StringBuilder validCodes = new StringBuilder(); int appended = 0; for (ErrorCode code : ErrorCode.values()) { if (code != ErrorCode.UNKNOWN) { if (appended++ > 0) validCodes.append(", "); validCodes.append(code.code); } } throw new IllegalArgumentException("Configured status code " + statusCode + " not supported! Please choose one of: " + validCodes.toString()); } // must always have a response message if sending an error code responseMsg = params.get("responseMessage", DEFAULT_RESPONSE_MSG); } } @Override public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) { return new IgnoreCommitOptimizeUpdateProcessor(rsp, this, next); } static class IgnoreCommitOptimizeUpdateProcessor extends UpdateRequestProcessor { private final SolrQueryResponse rsp; private final ErrorCode errorCode; private final String responseMsg; private final boolean ignoreOptimizeOnly; IgnoreCommitOptimizeUpdateProcessor(SolrQueryResponse rsp, IgnoreCommitOptimizeUpdateProcessorFactory factory, UpdateRequestProcessor next) { super(next); this.rsp = rsp; this.errorCode = factory.errorCode; this.responseMsg = factory.responseMsg; this.ignoreOptimizeOnly = factory.ignoreOptimizeOnly; } @Override public void processCommit(CommitUpdateCommand cmd) throws IOException { if (ignoreOptimizeOnly && !cmd.optimize) { // we're setup to only ignore optimize requests so it's OK to pass this commit on down the line if (next != null) next.processCommit(cmd); return; } if (cmd.getReq().getParams().getBool(DistributedUpdateProcessor.COMMIT_END_POINT, false)) { // this is a targeted commit from replica to leader needed for recovery, so can't be ignored if (next != null) next.processCommit(cmd); return; } final String cmdType = cmd.optimize ? "optimize" : "commit"; if (errorCode != null) { IgnoreCommitOptimizeUpdateProcessorFactory.log.info( "{} from client application ignored with error code: {}", cmdType, errorCode.code); rsp.setException(new SolrException(errorCode, responseMsg)); } else { // errorcode is null, treat as a success with an optional message warning the commit request was ignored IgnoreCommitOptimizeUpdateProcessorFactory.log.info( "{} from client application ignored with status code: 200", cmdType); if (responseMsg != null) { NamedList responseHeader = rsp.getResponseHeader(); if (responseHeader != null) { responseHeader.add("msg", responseMsg); } else { responseHeader = new SimpleOrderedMap(); responseHeader.add("msg", responseMsg); rsp.addResponseHeader(responseHeader); } } } } } } |
blob | {"1. Long method","2. Feature envy"} | t | f | f | 1. Long method, 2. Feature envy | blob | 0 | 2246 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/IgnoreCommitOptimizeUpdateProcessorFactory.java/#L42-L148 | 2 | 201 | 2246 | major |
| 510 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5190 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 2 | 510 | 5190 | major |
| 2425 | {"response": "YES I found bad smells", "the bad smells are": ["1. Blob", "2. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | 1. blob, 2. long method | t | t | f | 1. blob, 2. long method | data class | 0 | 14444 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 2425 | 14444 | critical |
| 520 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
blob | \n1. long method | t | t | f | \\n1. long method | blob | 0 | 5405 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 520 | 5405 | critical |
| 683 | YES I found bad smells the bad smells are: 1.Misleading indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | Misleading indentation | t | f | f | .Misleading indentation | data class | 0 | 6610 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 2 | 683 | 6610 | minor |
| 432 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class InvalidStateTransitionException extends Exception { private Enum currentState; private Enum event; public InvalidStateTransitionException(Enum currentState, Enum event) { super("Invalid event: " + event + " at " + currentState); this.currentState = currentState; this.event = event; } public Enum getCurrentState() { return currentState; } public Enum getEvent() { return event; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 4281 | https://github.com/apache/incubator-ambari/blob/bf747346312170834c6beb89a60c8624b47aa288/ambari-server/src/main/java/org/apache/ambari/server/state/fsm/InvalidStateTransitionException.java/#L25-L45 | 2 | 432 | 4281 | critical |
| 686 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Parser { public static GetOrderReferenceDetailsResponseData getOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final GetOrderReferenceDetailsResponse response = marshalXML(GetOrderReferenceDetailsResponse.class, rawResponse); return new GetOrderReferenceDetailsResponseData(response, rawResponse); } public static SetOrderReferenceDetailsResponseData setOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final SetOrderReferenceDetailsResponse response = marshalXML(SetOrderReferenceDetailsResponse.class, rawResponse); return new SetOrderReferenceDetailsResponseData(response, rawResponse); } public static AuthorizeResponseData getAuthorizeData(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeResponse response = marshalXML(AuthorizeResponse.class, rawResponse); return new AuthorizeResponseData(response, rawResponse); } public static GetAuthorizationDetailsResponseData getAuthorizationDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetAuthorizationDetailsResponse response = marshalXML(GetAuthorizationDetailsResponse.class, rawResponse); return new GetAuthorizationDetailsResponseData(response, rawResponse); } public static CaptureResponseData getCapture(ResponseData rawResponse) throws AmazonServiceException { final CaptureResponse response = marshalXML(CaptureResponse.class, rawResponse); return new CaptureResponseData(response, rawResponse); } public static GetCaptureDetailsResponseData getCaptureDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetCaptureDetailsResponse response = marshalXML(GetCaptureDetailsResponse.class, rawResponse); return new GetCaptureDetailsResponseData(response, rawResponse); } public static ConfirmOrderReferenceResponseData confirmOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ConfirmOrderReferenceResponse response = marshalXML(ConfirmOrderReferenceResponse.class, rawResponse); return new ConfirmOrderReferenceResponseData(response, rawResponse); } public static CloseAuthorizationResponseData closeAuthorizationResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseAuthorizationResponse response = marshalXML(CloseAuthorizationResponse.class, rawResponse); return new CloseAuthorizationResponseData(response, rawResponse); } public static CancelOrderReferenceResponseData getCancelOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CancelOrderReferenceResponse response = marshalXML(CancelOrderReferenceResponse.class, rawResponse); return new CancelOrderReferenceResponseData(response, rawResponse); } public static CloseOrderReferenceResponseData getCloseOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CloseOrderReferenceResponse response = marshalXML(CloseOrderReferenceResponse.class, rawResponse); return new CloseOrderReferenceResponseData(response, rawResponse); } public static RefundResponseData getRefundData(ResponseData rawResponse) throws AmazonServiceException { final RefundResponse response = marshalXML(RefundResponse.class, rawResponse); return new RefundResponseData(response, rawResponse); } public static GetRefundDetailsResponseData getRefundDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetRefundDetailsResponse response = marshalXML(GetRefundDetailsResponse.class, rawResponse); return new GetRefundDetailsResponseData(response, rawResponse); } public static GetBillingAgreementDetailsResponseData getBillingAgreementDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetBillingAgreementDetailsResponse response = marshalXML(GetBillingAgreementDetailsResponse.class, rawResponse); return new GetBillingAgreementDetailsResponseData(response, rawResponse); } public static SetBillingAgreementDetailsResponseData getSetBillingAgreementDetailsResponse(ResponseData rawResponse) throws AmazonServiceException { final SetBillingAgreementDetailsResponse response = marshalXML(SetBillingAgreementDetailsResponse.class, rawResponse); return new SetBillingAgreementDetailsResponseData(response, rawResponse); } public static ValidateBillingAgreementResponseData getValidateBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ValidateBillingAgreementResponse response = marshalXML(ValidateBillingAgreementResponse.class, rawResponse); return new ValidateBillingAgreementResponseData(response, rawResponse); } public static ConfirmBillingAgreementResponseData confirmBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ConfirmBillingAgreementResponse response = marshalXML(ConfirmBillingAgreementResponse.class, rawResponse); return new ConfirmBillingAgreementResponseData(response, rawResponse); } public static AuthorizeOnBillingAgreementResponseData getAuthorizeOnBillingAgreement(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeOnBillingAgreementResponse response = marshalXML(AuthorizeOnBillingAgreementResponse.class, rawResponse); return new AuthorizeOnBillingAgreementResponseData(response, rawResponse); } public static CloseBillingAgreementResponseData closeBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseBillingAgreementResponse response = marshalXML(CloseBillingAgreementResponse.class, rawResponse); return new CloseBillingAgreementResponseData(response, rawResponse); } public static GetProviderCreditDetailsResponseData getGetProviderCreditDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditDetailsResponse response = marshalXML(GetProviderCreditDetailsResponse.class, rawResponse); return new GetProviderCreditDetailsResponseData(response, rawResponse); } public static GetProviderCreditReversalDetailsResponseData getProviderCreditReversalDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditReversalDetailsResponse response = marshalXML(GetProviderCreditReversalDetailsResponse.class, rawResponse); return new GetProviderCreditReversalDetailsResponseData(response, rawResponse); } public static ReverseProviderCreditResponseData getReverseProviderCreditResponseData(ResponseData rawResponse) throws AmazonServiceException { final ReverseProviderCreditResponse response = marshalXML(ReverseProviderCreditResponse.class, rawResponse); return new ReverseProviderCreditResponseData(response, rawResponse); } public static GetServiceStatusResponseData getServiceStatus( ResponseData rawResponse) throws AmazonServiceException { final GetServiceStatusResponse response = marshalXML( GetServiceStatusResponse.class, rawResponse); return new GetServiceStatusResponseData(response, rawResponse); } public static CreateOrderReferenceForIdResponseData createOrderReferenceForId( ResponseData rawResponse) throws AmazonServiceException { final CreateOrderReferenceForIdResponse response = marshalXML( CreateOrderReferenceForIdResponse.class, rawResponse); return new CreateOrderReferenceForIdResponseData(response, rawResponse); } public static ListOrderReferenceResponseData listOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceResponse response = marshalXML(ListOrderReferenceResponse.class, rawResponse); return new ListOrderReferenceResponseData(response, rawResponse); } public static ListOrderReferenceByNextTokenResponseData listOrderReferenceByNextToken(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceByNextTokenResponse response = marshalXML(ListOrderReferenceByNextTokenResponse.class, rawResponse); return new ListOrderReferenceByNextTokenResponseData(response, rawResponse); } public static SetOrderAttributesResponseData setOrderAttributes(ResponseData rawResponse) throws AmazonServiceException { final SetOrderAttributesResponse response = marshalXML(SetOrderAttributesResponse.class, rawResponse); return new SetOrderAttributesResponseData(response, rawResponse); } public static GetMerchantAccountStatusResponseData getMerchantAccountStatus(ResponseData rawResponse) throws AmazonServiceException { final GetMerchantAccountStatusResponse response = marshalXML(GetMerchantAccountStatusResponse.class, rawResponse); return new GetMerchantAccountStatusResponseData(response, rawResponse); } public static T marshalXML(Class clazz, ResponseData rawResponse) throws AmazonServiceException { try { if (rawResponse.getStatusCode() == 200) { T responseObject = null; final JAXBContext context = JAXBContext.newInstance(clazz); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); responseObject = (T) unmarshaller.unmarshal(xmlStreamReader); return responseObject; } else { generateErrorException(rawResponse); } } catch (JAXBException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } return null; } public static void generateErrorException(ResponseData rawResponse) throws AmazonServiceException, JAXBException { final JAXBContext context = JAXBContext.newInstance(ErrorResponse.class); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); try { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); final ErrorResponse result = (ErrorResponse) unmarshaller.unmarshal(xmlStreamReader); throw new AmazonServiceException(result, rawResponse); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 6625 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/parser/Parser.java/#L57-L252 | 1 | 686 | 6625 | major |
| 2658 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 15186 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 2658 | 15186 | major |
| 2121 | YES I found bad smells the bad smells are: 1. Feature envy: The method "createRepositoryManager" is accessing multiple properties of the LuceneIndexForPartitionedRegion class instead of the properties of the LuceneRepositoryManager class. 2. Long method: The methods "isIndexingInProgress" and "createLuceneListenersAndFileChunkRegions" are long and could benefit from being split into smaller, more manageable methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | Feature envy: The method "createRepositoryManager" is accessing multiple properties of the LuceneIndexForPartitionedRegion class instead of the properties of the LuceneRepositoryManager class2 Long method: The methods "isIndexingInProgress" and "createLuceneListenersAndFileChunkRegions" are long and could benefit from being split into smaller, more manageable methods | t | f | f | . Feature envy: The method "createRepositoryManager" is accessing multiple properties of the LuceneIndexForPartitionedRegion class instead of the properties of the LuceneRepositoryManager class.2. Long method: The methods "isIndexingInProgress" and "createLuceneListenersAndFileChunkRegions" are long and could benefit from being split into smaller, more manageable methods. | blob | 0 | 13213 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 2121 | 13213 | minor |
| 400 | { "output": "YES I found bad smells" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CoordActionQueryExecutor extends QueryExecutor { public enum CoordActionQuery { UPDATE_COORD_ACTION, UPDATE_COORD_ACTION_STATUS_PENDING_TIME, UPDATE_COORD_ACTION_FOR_INPUTCHECK, UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK, UPDATE_COORD_ACTION_DEPENDENCIES, UPDATE_COORD_ACTION_FOR_START, UPDATE_COORD_ACTION_FOR_MODIFIED_DATE, UPDATE_COORD_ACTION_RERUN, GET_COORD_ACTION, GET_COORD_ACTION_STATUS, GET_COORD_ACTIVE_ACTIONS_COUNT_BY_JOBID, GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME, GET_COORD_ACTIONS_STATUS_UNIGNORED, GET_COORD_ACTIONS_PENDING_COUNT, GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE, GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE, GET_TERMINATED_ACTIONS_FOR_DATES, GET_TERMINATED_ACTION_IDS_FOR_DATES, GET_ACTIVE_ACTIONS_FOR_DATES, GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN, GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN, GET_COORD_ACTION_FOR_SLA, GET_COORD_ACTION_FOR_INPUTCHECK }; private static CoordActionQueryExecutor instance = new CoordActionQueryExecutor(); private CoordActionQueryExecutor() { } public static QueryExecutor getInstance() { return CoordActionQueryExecutor.instance; } @Override public Query getUpdateQuery(CoordActionQuery namedQuery, CoordinatorActionBean actionBean, EntityManager em) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); switch (namedQuery) { case UPDATE_COORD_ACTION: query.setParameter("actionNumber", actionBean.getActionNumber()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("consoleUrl", actionBean.getConsoleUrl()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("timeOut", actionBean.getTimeOut()); query.setParameter("trackerUri", actionBean.getTrackerUri()); query.setParameter("type", actionBean.getType()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("jobId", actionBean.getJobId()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("nominalTime", actionBean.getNominalTimestamp()); query.setParameter("slaXml", actionBean.getSlaXmlBlob()); query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_STATUS_PENDING_TIME: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("pending", actionBean.getPending()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_DEPENDENCIES: query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_START: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("pending", actionBean.getPending()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_MODIFIED_DATE: query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_RERUN: query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("status", actionBean.getStatusStr()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("rerunTime", actionBean.getRerunTimestamp()); query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + namedQuery.name()); } return query; } @Override public Query getSelectQuery(CoordActionQuery namedQuery, EntityManager em, Object... parameters) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); CoordActionQuery caQuery = (CoordActionQuery) namedQuery; switch (caQuery) { case GET_COORD_ACTION: case GET_COORD_ACTION_STATUS: case GET_COORD_ACTION_FOR_SLA: case GET_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("id", parameters[0]); break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: query.setParameter("jobId", parameters[0]); break; case GET_COORD_ACTIONS_PENDING_COUNT: query.setParameter("jobId", parameters[0]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: query.setParameter("ids", parameters[0]); break; case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: query.setParameter("jobId", parameters[0]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: case GET_TERMINATED_ACTION_IDS_FOR_DATES: case GET_ACTIVE_ACTIONS_FOR_DATES: query.setParameter("jobId", parameters[0]); query.setParameter("startTime", new Timestamp(((Date) parameters[1]).getTime())); query.setParameter("endTime", new Timestamp(((Date) parameters[2]).getTime())); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); query.setParameter("currentTime", new Timestamp(new Date().getTime())); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + caQuery.name()); } return query; } @Override public int executeUpdate(CoordActionQuery namedQuery, CoordinatorActionBean jobBean) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getUpdateQuery(namedQuery, jobBean, em); int ret = jpaService.executeUpdate(namedQuery.name(), query, em); return ret; } @Override public CoordinatorActionBean get(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { CoordinatorActionBean bean = getIfExist(namedQuery, parameters); if (bean == null) { throw new JPAExecutorException(ErrorCode.E0605, getSelectQuery(namedQuery, Services.get().get(JPAService.class).getEntityManager(), parameters).toString()); } return bean; } @Override public CoordinatorActionBean getIfExist(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { return null; } CoordinatorActionBean bean = constructBean(namedQuery, ret); return bean; } @Override public List getList(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); List retList = (List) jpaService.executeGetList(namedQuery.name(), query, em); List beanList = new ArrayList(); if (retList != null) { for (Object ret : retList) { beanList.add(constructBean(namedQuery, ret)); } } return beanList; } private CoordinatorActionBean constructBean(CoordActionQuery namedQuery, Object ret) throws JPAExecutorException { CoordinatorActionBean bean; Object[] arr; switch (namedQuery) { case GET_COORD_ACTION: bean = (CoordinatorActionBean) ret; break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: bean = new CoordinatorActionBean(); bean.setJobId((String) ret); break; case GET_COORD_ACTION_STATUS: bean = new CoordinatorActionBean(); bean.setStatusStr((String)ret); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setStatusStr((String)arr[0]); bean.setPending((Integer)arr[1]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setNominalTime((Timestamp)arr[1]); bean.setCreatedTime((Timestamp)arr[2]); bean.setActionXmlBlob((StringBlob)arr[3]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: bean = (CoordinatorActionBean) ret; break; case GET_TERMINATED_ACTION_IDS_FOR_DATES: bean = new CoordinatorActionBean(); bean.setId((String) ret); break; case GET_ACTIVE_ACTIONS_FOR_DATES: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); bean.setNominalTime((Timestamp) arr[5]); bean.setCreatedTime((Timestamp) arr[6]); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPushMissingDependenciesBlob((StringBlob) arr[4]); break; case GET_COORD_ACTION_FOR_SLA: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setJobId((String) arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setLastModifiedTime((Timestamp) arr[4]); break; case GET_COORD_ACTION_FOR_INPUTCHECK: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setActionNumber((Integer) arr[1]); bean.setJobId((String) arr[2]); bean.setStatus(CoordinatorAction.Status.valueOf((String) arr[3])); bean.setRunConfBlob((StringBlob) arr[4]); bean.setNominalTime(DateUtils.toDate((Timestamp) arr[5])); bean.setCreatedTime(DateUtils.toDate((Timestamp) arr[6])); bean.setActionXmlBlob((StringBlob) arr[7]); bean.setMissingDependenciesBlob((StringBlob) arr[8]); bean.setPushMissingDependenciesBlob((StringBlob) arr[9]); bean.setTimeOut((Integer) arr[10]); bean.setExternalId((String) arr[11]); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot construct action bean for " + namedQuery.name()); } return bean; } @Override public Object getSingleValue(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { throw new JPAExecutorException(ErrorCode.E0604, query.toString()); } return ret; } } |
blob | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 4082 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/executor/jpa/CoordActionQueryExecutor.java/#L40-L383 | 1 | 400 | 4082 | major |
| 4604 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12251 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 4604 | 12251 | minor |
| 1541 | {"response": "YES I found bad smells", "detected bad smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } } |
blob | t | f | f | blob | 0 | 11237 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 | 1 | 1541 | 11237 | major | ||
| 5774 | NO, I did not find any bad smell | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | f | f | f | long method | 0 | 14902 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5774 | 14902 | major | ||
| 1467 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11038 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 | 2 | 1467 | 11038 | critical |
| 71 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class XPathConstants { /** * Private constructor to prevent instantiation. */ private XPathConstants() { } /** * The XPath 1.0 number data type. * * Maps to Java {@link Double}. */ public static final QName NUMBER = new QName("http://www.w3.org/1999/XSL/Transform", "NUMBER"); /** * The XPath 1.0 string data type. * * Maps to Java {@link String}. */ public static final QName STRING = new QName("http://www.w3.org/1999/XSL/Transform", "STRING"); /** * The XPath 1.0 boolean data type. * * Maps to Java {@link Boolean}. */ public static final QName BOOLEAN = new QName("http://www.w3.org/1999/XSL/Transform", "BOOLEAN"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.NodeList}. */ public static final QName NODESET = new QName("http://www.w3.org/1999/XSL/Transform", "NODESET"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.Node}. */ public static final QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE"); /** * The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom". */ public static final String DOM_OBJECT_MODEL = "http://java.sun.com/jaxp/xpath/dom"; } |
data class | long method | t | t | f | long method | data class | 0 | 1103 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathConstants.java/#L32-L78 | 2 | 71 | 1103 | critical |
| 2650 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | f | f | f | long method | 0 | 15167 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 2650 | 15167 | minor | ||
| 1672 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 11637 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 1672 | 11637 | minor |
| 441 | YES, I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Inconsistent naming conventions (e.g. type, Type) 5. Inconsistent spacing/tabs 6. Mixing of responsibilities (e.g. converting types, analyzing type) 7. Use of instanceof 8. Complex nested conditionals 9. Magic numbers/strings (e.g. "Array", "Map") 10. Dependency on external classes (e.g. Primitives) 11. Lack of proper comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Duplicated code2 Long method3 Feature envy4 Inconsistent naming conventions (eg type, Type)5 Inconsistent spacing/tabs6 Mixing of responsibilities (eg converting types, analyzing type)7 Use of instanceof8 Complex nested conditionals9 Magic numbers/strings (eg "Array", "Map") | t | f | f | . Duplicated code2. Long method3. Feature envy4. Inconsistent naming conventions (e.g. type, Type)5. Inconsistent spacing/tabs6. Mixing of responsibilities (e.g. converting types, analyzing type)7. Use of instanceof8. Complex nested conditionals9. Magic numbers/strings (e.g. "Array", "Map") | data class | 0 | 4302 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 441 | 4302 | critical |
| 2093 | { "answer": "YES I found bad smells", "bad smells are": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component("aws-ddbstream") public class DdbStreamComponent extends DefaultComponent { @Metadata private String accessKey; @Metadata private String secretKey; @Metadata private String region; @Metadata(label = "advanced") private DdbStreamConfiguration configuration; public DdbStreamComponent() { this(null); } public DdbStreamComponent(CamelContext context) { super(context); this.configuration = new DdbStreamConfiguration(); registerExtension(new DdbStreamComponentVerifierExtension()); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { DdbStreamConfiguration configuration = this.configuration.copy(); configuration.setTableName(remaining); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Table name must be specified."); } configuration.setTableName(remaining); if (ObjectHelper.isEmpty(configuration.getAccessKey())) { setAccessKey(accessKey); } if (ObjectHelper.isEmpty(configuration.getSecretKey())) { setSecretKey(secretKey); } if (ObjectHelper.isEmpty(configuration.getRegion())) { setRegion(region); } if (configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("amazonDDBStreamsClient or accessKey and secretKey must be specified"); } DdbStreamEndpoint endpoint = new DdbStreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); return endpoint; } public DdbStreamConfiguration getConfiguration() { return configuration; } /** * The AWS DDB stream default configuration */ public void setConfiguration(DdbStreamConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return configuration.getAccessKey(); } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { configuration.setAccessKey(accessKey); } public String getSecretKey() { return configuration.getSecretKey(); } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { configuration.setSecretKey(secretKey); } public String getRegion() { return configuration.getRegion(); } /** * Amazon AWS Region */ public void setRegion(String region) { configuration.setRegion(region); } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 13140 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamComponent.java/#L28-L122 | 1 | 2093 | 13140 | minor |
| 5299 | found. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 14830 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L33809-L33879 | 2 | 5299 | 14830 | major | ||
| 1379 | YES, I found bad smells - long method, feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | t | f | f | long method | 0 | 10817 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 2 | 1379 | 10817 | critical | ||
| 1742 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 11845 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 2 | 1742 | 11845 | minor |
| 365 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 3717 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 | 2 | 365 | 3717 | minor |
| 801 | { "NO, I did not find any bad smell" : "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 7591 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 1 | 801 | 7591 | major |
| 271 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
blob | data class | t | t | f | data class | blob | 0 | 2918 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 1 | 271 | 2918 | minor |
| 454 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ExpressionNode { String evaluateAsString(Context context); Object evaluateAsObject(Context context); long evaluateAsLong(Context context); double evaluateAsDouble(Context context); boolean evaluateAsBoolean(Context context); } |
data class | Long method | t | f | f | . Long method | data class | 0 | 4439 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java/#L27-L39 | 2 | 454 | 4439 | critical |
| 4109 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int count = readUnsignedShort(); requires = new Require[count]; for (int i = 0; i < count; i++) { requires[i] = new Require(readUnsignedShort(), readUnsignedShort(), readUnsignedShort()); } count = readUnsignedShort(); exports = new Export[count]; for (int i = 0; i < count; i++) { int index = readUnsignedShort(); int flags = readUnsignedShort(); int toCount = readUnsignedShort(); int[] to = new int[toCount]; for (int j = 0; j < toCount; j++) { to[j] = readUnsignedShort(); } exports[i] = new Export(index, flags, to); } count = readUnsignedShort(); |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 10822 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java/#L335-L355 | 1 | 4109 | 10822 | major |
| 242 | {"response": "YES I found bad smells", "the bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 2644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 2 | 242 | 2644 | major |
| 1954 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
blob | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | blob | 0 | 12540 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 2 | 1954 | 12540 | minor |
| 5400 | { "message": "Please provide the Java code you would like me to check for code smells." } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | Not specified | f | f | f | false | 0 | 15175 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 5400 | 15175 | minor | |
| 2621 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | long method | t | t | f | long method | data class | 0 | 15056 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 2621 | 15056 | minor |
| 980 | YES I found bad smells the bad smells are: 1. Primitive obsession, 2. Long parameter list 3. Feature envy 4. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Primitive obsession, 2 Long parameter list3 Feature envy4 Long method | t | f | f | . Primitive obsession, 2. Long parameter list3. Feature envy4. Long method | data class | 0 | 8852 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 2 | 980 | 8852 | major |
| 2473 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Nested conditionals 5. Lack of encapsulation/modularity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } } |
blob | Long method2 Feature envy3 Duplicate code4 Nested conditionals5 Lack of encapsulation/modularity | t | f | f | . Long method2. Feature envy3. Duplicate code4. Nested conditionals5. Lack of encapsulation/modularity | blob | 0 | 14582 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 | 2 | 2473 | 14582 | major |
| 2443 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
blob | long method | t | t | f | long method | blob | 0 | 14485 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 1 | 2443 | 14485 | minor |
| 2501 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractClientProvider { public AbstractClientProvider() { } /** * Generates a fixed format of application tags given one or more of * application name, version and description. This allows subsequent query for * an application with a name only, version only or description only or any * combination of those as filters. * * @param appName name of the application * @param appVersion version of the application * @param appDescription brief description of the application * @return */ public static final Set createApplicationTags(String appName, String appVersion, String appDescription) { Set tags = new HashSet<>(); tags.add(ServiceUtils.createNameTag(appName)); if (appVersion != null) { tags.add(ServiceUtils.createVersionTag(appVersion)); } if (appDescription != null) { tags.add(ServiceUtils.createDescriptionTag(appDescription)); } return tags; } /** * Validate the artifact. * @param artifact */ public abstract void validateArtifact(Artifact artifact, String compName, FileSystem fileSystem) throws IOException; protected abstract void validateConfigFile(ConfigFile configFile, String compName, FileSystem fileSystem) throws IOException; /** * Validate the config files. * @param configFiles config file list * @param fs file system */ public void validateConfigFiles(List configFiles, String compName, FileSystem fs) throws IOException { Set destFileSet = new HashSet<>(); for (ConfigFile file : configFiles) { if (file.getType() == null) { throw new IllegalArgumentException("File type is empty"); } ConfigFile.TypeEnum fileType = file.getType(); if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) { if (StringUtils.isEmpty(file.getSrcFile()) && !file.getProperties().containsKey(CONTENT)) { throw new IllegalArgumentException(MessageFormat.format("For {0} " + "format, either src_file must be specified in ConfigFile," + " or the \"{1}\" key must be specified in " + "the 'properties' field of ConfigFile. ", ConfigFile.TypeEnum.TEMPLATE, CONTENT)); } } else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals( ConfigFile.TypeEnum.ARCHIVE)) { if (!file.getProperties().isEmpty()) { throw new IllegalArgumentException(String .format("For %s format, should not specify any 'properties.'", fileType)); } String srcFile = file.getSrcFile(); if (srcFile == null || srcFile.isEmpty()) { throw new IllegalArgumentException(String.format( "For %s format, should make sure that srcFile is specified", fileType)); } FileStatus fileStatus = fs.getFileStatus(new Path(srcFile)); if (fileStatus != null && fileStatus.isDirectory()) { throw new IllegalArgumentException("srcFile=" + srcFile + " is a directory, which is not supported."); } } if (!StringUtils.isEmpty(file.getSrcFile())) { Path p = new Path(file.getSrcFile()); if (!fs.exists(p)) { throw new IllegalArgumentException( "Specified src_file does not exist on " + fs.getScheme() + ": " + file.getSrcFile()); } } if (StringUtils.isEmpty(file.getDestFile())) { throw new IllegalArgumentException("dest_file is empty."); } if (destFileSet.contains(file.getDestFile())) { throw new IllegalArgumentException( "Duplicated ConfigFile exists: " + file.getDestFile()); } destFileSet.add(file.getDestFile()); java.nio.file.Path destPath = Paths.get(file.getDestFile()); if (!destPath.isAbsolute() && destPath.getNameCount() > 1) { throw new IllegalArgumentException("Non-absolute dest_file has more " + "than one path element"); } // provider-specific validation validateConfigFile(file, compName, fs); } } } |
blob | 1. long method, 2. data class | t | t | f | 1. long method, 2. data class | blob | 0 | 14658 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/AbstractClientProvider.java/#L38-L150 | 1 | 2501 | 14658 | minor |
| 2863 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 1961 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/thrift/ClientService.java/#L33559-L33561 | 2 | 2863 | 1961 | minor | ||
| 2296 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | f | f | f | data class | 0 | 14009 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 2 | 2296 | 14009 | critical | ||
| 2851 | {"response": "YES I found bad smells", "bad smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getDisplayName() { return AssignmentsTestLanguageLanguage.INSTANCE.getDisplayName(); } |
feature envy | blob | t | t | f | blob | feature envy | 0 | 1807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.core.idea.tests/src-gen/org/eclipse/xtext/parser/assignments/idea/highlighting/AssignmentsTestLanguageBaseColorSettingsPage.java/#L13-L16 | 1 | 2851 | 1807 | major |
| 2111 | {"message": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13188 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 1 | 2111 | 13188 | minor |
| 4204 | { "output": "YES I found bad smells\nthe bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
blob | 2. data class | t | t | f | 2. data class | blob | 0 | 11063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 4204 | 11063 | minor |
| 1783 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 11967 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 | 1 | 1783 | 11967 | critical |
| 4085 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10772 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 1 | 4085 | 10772 | major |
| 2605 | YES I found bad smells: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 15028 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 2 | 2605 | 15028 | critical |
| 798 | YES I found bad smells the bad smells are: 1.Long method, 2.Long parameter list, 3.Inappropriate intimacy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RowReadSupport extends ReadSupport { private TypeInformation returnTypeInfo; @Override public ReadContext init(InitContext initContext) { checkNotNull(initContext, "initContext"); returnTypeInfo = ParquetSchemaConverter.fromParquetType(initContext.getFileSchema()); return new ReadContext(initContext.getFileSchema()); } @Override public RecordMaterializer prepareForRead( Configuration configuration, Map keyValueMetaData, MessageType fileSchema, ReadContext readContext) { return new RowMaterializer(readContext.getRequestedSchema(), returnTypeInfo); } } |
data class | Long method, 2Long parameter list, 3Inappropriate intimacy | t | f | f | .Long method, 2.Long parameter list, 3.Inappropriate intimacy. | data class | 0 | 7569 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/RowReadSupport.java/#L37-L54 | 2 | 798 | 7569 | minor |
| 849 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class SearchFirstStringNode extends Node { private static final int[] UNINTIALIZED_CACHED_INDICES = new int[0]; private final VectorLengthProfile targetLengthProfile = VectorLengthProfile.create(); private final VectorLengthProfile elementsLengthProfile = VectorLengthProfile.create(); private final ValueProfile targetClassProfile = ValueProfile.createClassProfile(); private final ValueProfile elementsClassProfile = ValueProfile.createClassProfile(); @Child private StringEqualsNode stringEquals = CompareStringNode.createEquals(); @Child private CompareStringNode stringStartsWith; @Child private StringEqualsNode equalsDuplicate; private final NACheck elementsNACheck = NACheck.create(); private final NACheck targetNACheck = NACheck.create(); private final BranchProfile everFoundDuplicate = BranchProfile.create(); private final BranchProfile seenInvalid = BranchProfile.create(); /** Instead of using the notFoundStartIndex we use NA. */ private final boolean useNAForNotFound; private final boolean exactMatch; @CompilationFinal(dimensions = 1) private int[] cachedIndices; private SearchFirstStringNode(boolean exactMatch, boolean useNAForNotFound) { this.exactMatch = exactMatch; this.useNAForNotFound = useNAForNotFound; if (!exactMatch) { stringStartsWith = CompareStringNode.createStartsWith(); } } public RAbstractIntVector apply(RAbstractStringVector target, RAbstractStringVector elements, int notFoundStartIndex, RStringVector names) { RAbstractStringVector targetProfiled = targetClassProfile.profile(target); RAbstractStringVector elementsProfiled = elementsClassProfile.profile(elements); int targetLength = targetLengthProfile.profile(targetProfiled.getLength()); int elementsLength = elementsLengthProfile.profile(elementsProfiled.getLength()); targetNACheck.enable(target); elementsNACheck.enable(elements); if (cachedIndices == UNINTIALIZED_CACHED_INDICES) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = searchCached(targetProfiled, targetLength, elementsProfiled, elementsLength, names); } if (cachedIndices != null) { if (!isCacheValid(targetProfiled, targetLength, elementsProfiled, elementsLength, cachedIndices)) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = null; // set to generic // fallthrough to generic } else { assert sameVector(searchCached(target, targetLength, elements, elementsLength, names), cachedIndices); return RDataFactory.createIntVector(cachedIndices, true, names); } } return searchGeneric(targetProfiled, targetLength, elementsProfiled, elementsLength, notFoundStartIndex, false, names); } public static SearchFirstStringNode createNode(boolean exactMatch, boolean useNAForNotFound) { return new SearchFirstStringNode(exactMatch, useNAForNotFound); } private int[] searchCached(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, RStringVector names) { if (exactMatch) { RAbstractIntVector genericResult = searchGeneric(target, targetLength, elements, elementsLength, -1, true, names); if (genericResult != null) { return genericResult.materialize().getReadonlyData(); } } return null; } private boolean isCacheValid(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int[] cached) { int cachedLength = cached.length; if (elementsLength != cachedLength) { seenInvalid.enter(); return false; } for (int i = 0; i < cachedLength; i++) { int cachedIndex = cached[i]; String cachedElement = elements.getDataAt(i); int cachedElementHash = cachedElement.hashCode(); assert !elementsNACheck.check(cachedElement) && cachedElement.length() > 0; int cachedTranslatedIndex = cachedIndex - 1; for (int j = 0; j < cachedTranslatedIndex; j++) { String targetString = target.getDataAt(j); if (!targetNACheck.check(targetString) && stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } if (cachedTranslatedIndex < targetLength) { String targetString = target.getDataAt(cachedTranslatedIndex); if (!targetNACheck.check(targetString) && !stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } else { seenInvalid.enter(); return false; } } return true; } private static boolean sameVector(int[] a, int[] b) { if (a == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } private final BranchProfile notFoundProfile = BranchProfile.create(); private final ConditionProfile hashingProfile = ConditionProfile.createBinaryProfile(); private RAbstractIntVector searchGeneric(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int notFoundStartIndex, boolean nullOnNotFound, RStringVector names) { int[] indices = new int[elementsLength]; boolean resultComplete = true; long hashingCost = targetLength * 10L + 10 /* constant overhead */; long lookupCost = elementsLength * 2L; long nestedLoopCost = targetLength * (long) elementsLength; NonRecursiveHashMapCharacter map; if (hashingProfile.profile(nestedLoopCost > hashingCost + lookupCost)) { map = new NonRecursiveHashMapCharacter(targetLength); for (int i = 0; i < targetLength; i++) { String name = target.getDataAt(i); if (!targetNACheck.check(name)) { map.put(name, i); } } } else { map = null; } int notFoundIndex = notFoundStartIndex; for (int i = 0; i < elementsLength; i++) { String element = elements.getDataAt(i); boolean isElementNA = elementsNACheck.check(element) || element.length() == 0; if (!isElementNA) { int index; if (map != null) { index = map.get(element); if (!exactMatch && index < 0) { // the map is only good for exact matches index = findNonExactIndex(target, targetLength, element); } } else { index = findIndex(target, targetLength, element); } if (index >= 0) { indices[i] = index + 1; continue; } } notFoundProfile.enter(); if (nullOnNotFound) { return null; } else { int prevDuplicateIndex = -1; if (!isElementNA) { prevDuplicateIndex = findFirstDuplicate(elements, element, i); } int nextIndex; if (prevDuplicateIndex == -1) { if (useNAForNotFound) { resultComplete = false; nextIndex = RRuntime.INT_NA; } else { nextIndex = ++notFoundIndex; } } else { nextIndex = indices[prevDuplicateIndex]; } indices[i] = nextIndex; } } return RDataFactory.createIntVector(indices, resultComplete && elements.isComplete(), names); } private int findNonExactIndex(RAbstractStringVector target, int targetLength, String element) { assert !exactMatch; int nonExactIndex = -1; for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { return -1; } } } } return nonExactIndex; } private int findIndex(RAbstractStringVector target, int targetLength, String element) { int nonExactIndex = -1; int elementHash = element.hashCode(); for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringEquals.executeCompare(element, elementHash, targetValue)) { return j; } if (!exactMatch) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { nonExactIndex = -2; } } } } } return nonExactIndex; } private int findFirstDuplicate(RAbstractStringVector elements, String element, int currentIndex) { if (equalsDuplicate == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); equalsDuplicate = insert(CompareStringNode.createEquals()); } int elementHash = element.hashCode(); for (int j = 0; j < currentIndex; j++) { String otherElement = elements.getDataAt(j); if (!targetNACheck.check(otherElement) && equalsDuplicate.executeCompare(element, elementHash, otherElement)) { everFoundDuplicate.enter(); return j; } } return -1; } abstract static class CompareStringNode extends Node { public abstract boolean executeCompare(String a, String b); public static StringEqualsNode createEquals() { return new StringEqualsNode(); } public static StringStartsWithNode createStartsWith() { return new StringStartsWithNode(); } public static class StringEqualsNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); private final ConditionProfile hashEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(a.hashCode() != b.hashCode())) { return false; } return a.equals(b); } } public final boolean executeCompare(String a, int aHash, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(aHash != b.hashCode())) { return false; } return a.equals(b); } } } private static class StringStartsWithNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { return a.startsWith(b); } } } } } |
blob | f | f | f | blob | 0 | 7848 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/SearchFirstStringNode.java/#L46-L361 | 2 | 849 | 7848 | major | ||
| 5189 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 14509 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 2 | 5189 | 14509 | minor | ||
| 2685 | YES, I found bad smells. the bad smells are: 1. Long method 2. Duplicated code 3. Complex code 4. Lazy class 5. Inappropriate naming 6. Feature envy 7. Primitive Obsession 8. Large class 9. Multiple return statements 10. Message chain 11. Magic numbers 12. Use of raw types 13. Use of null values 14. Unused variables 15. Poor exception handling 16. Inconsistent formatting and indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } } |
blob | Long method2 Duplicated code3 Complex code4 Lazy class5 Inappropriate naming6 Feature envy7 Primitive Obsession8 Large class9 Multiple return statements | t | f | f | . Long method2. Duplicated code3. Complex code4. Lazy class5. Inappropriate naming6. Feature envy7. Primitive Obsession8. Large class9. Multiple return statements | blob | 0 | 15277 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 | 2 | 2685 | 15277 | minor |
| 1876 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12264 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 1876 | 12264 | minor |
| 1242 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10414 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 2 | 1242 | 10414 | minor |
| 2655 | YES I found bad smells the bad smells are: 1. Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation. 2. Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle. 3. Inconsistent naming convention: In some places, camel case is used to name variables (e.g. changeCidr) while in others, underscores are used (e.g. displayText), indicating a potential problem with consistency. 4. Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability. 5. Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition. 6. Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain. 7. Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation2 Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle3 Inconsistent naming convention: In some places, camel case is used to name variables (eg changeCidr) while in others, underscores are used (eg displayText), indicating a potential problem with consistency4 Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability5 Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition6 Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain7 Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code | t | f | f | . Feature envy: The methods in the UpdateNetworkCmd class access and manipulate properties from other classes, indicating a potential problem with encapsulation.2. Long method: The execute() method in the UpdateNetworkCmd class is quite long and performs multiple operations, indicating a potential problem with the Single Responsibility Principle.3. Inconsistent naming convention: In some places, camel case is used to name variables (e.g. changeCidr) while in others, underscores are used (e.g. displayText), indicating a potential problem with consistency.4. Magic number: There are several instances where specific numbers are used to represent a certain parameter, such as 0, false, or null, which could be replaced with named constants for better readability.5. Duplicate code: The getId() method is used in multiple places in the UpdateNetworkCmd class, which may indicate a problem with code repetition.6. Insufficient commenting: Some methods, such as the execute() method, lack thorough comments and documentation, which could make the code harder to understand and maintain.7. Inconsistent method ordering: The methods in the UpdateNetworkCmd class are not consistently ordered, making it harder to navigate and understand the code. | data class | 0 | 15181 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 2655 | 15181 | minor |
| 588 | {"answer": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 5858 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 | 1 | 588 | 5858 | critical |
| 1709 | {"response":"YES I found bad smells","bad smells are":["Long method","Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @KapuaProvider public class CredentialServiceImpl extends AbstractKapuaConfigurableService implements CredentialService { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialServiceImpl.class); public CredentialServiceImpl() { super(CredentialService.class.getName(), AuthenticationDomains.CREDENTIAL_DOMAIN, AuthenticationEntityManagerFactory.getInstance()); } @Override public Credential create(CredentialCreator credentialCreator) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialCreator, "credentialCreator"); ArgumentValidator.notNull(credentialCreator.getScopeId(), "credentialCreator.scopeId"); ArgumentValidator.notNull(credentialCreator.getUserId(), "credentialCreator.userId"); ArgumentValidator.notNull(credentialCreator.getCredentialType(), "credentialCreator.credentialType"); ArgumentValidator.notNull(credentialCreator.getCredentialStatus(), "credentialCreator.credentialStatus"); if (credentialCreator.getCredentialType() != CredentialType.API_KEY) { ArgumentValidator.notEmptyOrNull(credentialCreator.getCredentialPlainKey(), "credentialCreator.credentialKey"); } if (credentialCreator.getCredentialType() == CredentialType.PASSWORD) { // // Check if a PASSWORD credential already exists for the user CredentialListResult existingCredentials = findByUserId(credentialCreator.getScopeId(), credentialCreator.getUserId()); for (Credential credential : existingCredentials.getItems()) { if (credential.getCredentialType().equals(CredentialType.PASSWORD)) { throw new KapuaExistingCredentialException(CredentialType.PASSWORD); } } // // Validate Password regex ArgumentValidator.match(credentialCreator.getCredentialPlainKey(), CommonsValidationRegex.PASSWORD_REGEXP, "credentialCreator.credentialKey"); } // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credentialCreator.getScopeId())); // // Do create Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { em.beginTransaction(); // // Do pre persist magic on key values String fullKey = null; switch (credentialCreator.getCredentialType()) { case API_KEY: // Generate new api key SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH); byte[] bPre = new byte[preLength]; random.nextBytes(bPre); String pre = Base64.encodeToString(bPre).substring(0, preLength); byte[] bKey = new byte[keyLength]; random.nextBytes(bKey); String key = Base64.encodeToString(bKey); fullKey = pre + key; credentialCreator = new CredentialCreatorImpl(credentialCreator.getScopeId(), credentialCreator.getUserId(), credentialCreator.getCredentialType(), fullKey, credentialCreator.getCredentialStatus(), credentialCreator.getExpirationDate()); break; case PASSWORD: default: // Don't do nothing special break; } credential = CredentialDAO.create(em, credentialCreator); credential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); em.commit(); // // Do post persist magic on key values switch (credentialCreator.getCredentialType()) { case API_KEY: credential.setCredentialKey(fullKey); break; case PASSWORD: default: credential.setCredentialKey(fullKey); } } catch (Exception pe) { em.rollback(); throw KapuaExceptionUtils.convertPersistenceException(pe); } finally { em.close(); } return credential; } @Override public Credential update(Credential credential) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credential, "credential"); ArgumentValidator.notNull(credential.getId(), "credential.id"); ArgumentValidator.notNull(credential.getScopeId(), "credential.scopeId"); ArgumentValidator.notNull(credential.getUserId(), "credential.userId"); ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); ArgumentValidator.notEmptyOrNull(credential.getCredentialKey(), "credential.credentialKey"); // // Check access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, credential.getScopeId())); return entityManagerSession.onTransactedResult(em -> { Credential currentCredential = CredentialDAO.find(em, credential.getScopeId(), credential.getId()); if (currentCredential == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credential.getId()); } if (currentCredential.getCredentialType() != credential.getCredentialType()) { throw new KapuaIllegalArgumentException("credentialType", credential.getCredentialType().toString()); } // Passing attributes?? return CredentialDAO.update(em, credential); }); } @Override public Credential find(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // Validation of the fields ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); return entityManagerSession.onResult(em -> CredentialDAO.find(em, scopeId, credentialId)); } @Override public CredentialListResult query(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.query(em, query)); } @Override public long count(KapuaQuery query) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(query, "query"); ArgumentValidator.notNull(query.getScopeId(), "query.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, query.getScopeId())); return entityManagerSession.onResult(em -> CredentialDAO.count(em, query)); } @Override public void delete(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.delete, scopeId)); entityManagerSession.onTransactedAction(em -> { if (CredentialDAO.find(em, scopeId, credentialId) == null) { throw new KapuaEntityNotFoundException(Credential.TYPE, credentialId); } CredentialDAO.delete(em, scopeId, credentialId); }); } @Override public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, scopeId)); // // Build query CredentialQuery query = new CredentialQueryImpl(scopeId); QueryPredicate predicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); query.setPredicate(predicate); // // Query and return result return query(query); } @Override public Credential findByApiKey(String apiKey) throws KapuaException { // // Argument Validation ArgumentValidator.notEmptyOrNull(apiKey, "apiKey"); // // Do the find Credential credential = null; EntityManager em = AuthenticationEntityManagerFactory.getEntityManager(); try { // // Build search query KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance(); int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH); String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR); String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // // Build query KapuaQuery query = new CredentialQueryImpl(); AttributePredicateImpl typePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, CredentialType.API_KEY); AttributePredicateImpl keyPredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_KEY, apiKeyPreValue, Operator.STARTS_WITH); AndPredicateImpl andPredicate = new AndPredicateImpl(); andPredicate.and(typePredicate); andPredicate.and(keyPredicate); query.setPredicate(andPredicate); // // Query CredentialListResult credentialListResult = CredentialDAO.query(em, query); // // Parse the result credential = credentialListResult.getFirstItem(); } catch (Exception e) { throw KapuaExceptionUtils.convertPersistenceException(e); } finally { em.close(); } // // Check Access if (credential != null) { KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.read, credential.getId())); } return credential; } @Override public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException { // // Argument Validation ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(credentialId, "credentialId"); // // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); authorizationService.checkPermission(permissionFactory.newPermission(AuthenticationDomains.CREDENTIAL_DOMAIN, Actions.write, scopeId)); Credential credential = find(scopeId, credentialId); credential.setLoginFailures(0); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); update(credential); } private long countExistingCredentials(CredentialType credentialType, KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); KapuaQuery credentialQuery = credentialFactory.newQuery(scopeId); CredentialType ct = credentialType; QueryPredicate credentialTypePredicate = new AttributePredicateImpl<>(CredentialAttributes.CREDENTIAL_TYPE, ct); QueryPredicate userIdPredicate = new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId); QueryPredicate andPredicate = new AndPredicateImpl().and(credentialTypePredicate).and(userIdPredicate); credentialQuery.setPredicate(andPredicate); return count(credentialQuery); } //@ListenServiceEvent(fromAddress="account") //@ListenServiceEvent(fromAddress="user") public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOGGER.info("CredentialService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("user".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByUserId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } else if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteCredentialByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(scopeId); query.setPredicate(new AttributePredicateImpl<>(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { KapuaLocator locator = KapuaLocator.getInstance(); CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); CredentialQuery query = credentialFactory.newQuery(accountId); CredentialListResult credentialsToDelete = query(query); for (Credential c : credentialsToDelete.getItems()) { delete(c.getScopeId(), c.getId()); } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 11762 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java/#L60-L442 | 2 | 1709 | 11762 | major |
| 1599 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 11418 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 1 | 1599 | 11418 | critical |
| 689 | YES, I found bad smells the bad smells are: 1. Magic numbers (line 5, 6, 12, 13, 14) 2. Long method (main method) 3. Feature envy (Methods belonging to different classes but access the same data) 4. Temporary variables (row and cell) 5. Inconsistent indentation (line 3) 6. Unused code (lines 29, 30, 42, 43) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | Magic numbers (line 5, 6, | t | f | f | . Magic numbers (line 5, 6, | long method | 0 | 6635 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 2 | 689 | 6635 | major |
| 2253 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13685 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 2 | 2253 | 13685 | major |
| 1943 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 12503 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 2 | 1943 | 12503 | major |
| 2632 | YES I found bad smells the bad smells are: 1. Empty constructor 2. Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | Empty constructor2 Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object | t | f | f | . Empty constructor2. Feature envy: the set() method is using EntityReference instead of ReferenceProperty, indicating that the method is more interested in the reference object rather than the property object. | data class | 0 | 15108 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 2 | 2632 | 15108 | major |
| 2035 | YES I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 12828 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 2 | 2035 | 12828 | minor |
| 790 | YES, I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 7527 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 2 | 790 | 7527 | major |
| 3975 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | 1. blob | t | t | f | 1. blob | data class | 0 | 10430 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 3975 | 10430 | critical |
| 2643 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 15147 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 2 | 2643 | 15147 | major |
| 802 | { "response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 7592 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 2 | 802 | 7592 | minor |
| 1421 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 10929 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1421 | 10929 | minor |
| 1700 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
blob | "YES I found bad smells", "the bad smells are" | t | f | f | "YES I found bad smells", "the bad smells are" | blob | 0 | 11735 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 1700 | 11735 | major |
| 3891 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 30, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Thread) public static class DeleteTasksBenchmark { private StateManager manager; private Storage storage; private Set taskIds; @Param({"1000", "10000", "50000"}) private int numTasksToDelete; @Setup(Level.Trial) public void setUpStorage() { Injector injector = getInjector(); manager = injector.getInstance(StateManager.class); storage = injector.getInstance(Storage.class); storage.prepare(); } // JMH warns heavily against using `Invocation` but this test seems to meet the requirements // of using it. Each benchmark will take more than one ms and it avoids awkward logic to // setup storage before the benchmark. @Setup(Level.Invocation) public void setUp() { storage.write(new Storage.MutateWork.NoResult.Quiet() { @Override public void execute(Storage.MutableStoreProvider storeProvider) throws RuntimeException { taskIds = bulkInsertTasks(numTasksToDelete, storeProvider.getUnsafeTaskStore()); } }); } @Benchmark public Set run() { return storage.write((Storage.MutateWork.Quiet>) storeProvider -> { manager.deleteTasks(storeProvider, taskIds); return taskIds; }); } } |
blob | long method | t | t | f | long method | blob | 0 | 10181 | https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/jmh/java/org/apache/aurora/benchmark/StateManagerBenchmarks.java/#L117-L159 | 1 | 3891 | 10181 | major |
| 2566 | YES, I found bad smells. The bad smells are: 1. Long class 2. Feature envy 3. Long parameter list 4. Inappropriate coupling or dependency 5. Long method 6. Spaghetti code 7. Inconsistent naming conventions 8. Lack of abstraction/modularity 9. Inconsistent commenting/documentation 10. Lack of encapsulation 11. Too many nested levels of code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | Long class2 Feature envy3 Long parameter list4 Inappropriate coupling or dependency5 Long method6 Spaghetti code7 Inconsistent naming conventions8 Lack of abstraction/modularity 9 Inconsistent commenting/documentation | t | f | f | . Long class2. Feature envy3. Long parameter list4. Inappropriate coupling or dependency5. Long method6. Spaghetti code7. Inconsistent naming conventions8. Lack of abstraction/modularity 9. Inconsistent commenting/documentation | blob | 0 | 14868 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 2 | 2566 | 14868 | minor |
| 1468 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
blob | data class | t | t | f | data class | blob | 0 | 11044 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 1468 | 11044 | major |
| 2362 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14252 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 2362 | 14252 | minor |
| 4824 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JAXRSOutInterceptor extends AbstractOutDatabindingInterceptor { private static final Logger LOG = LogUtils.getL7dLogger(JAXRSOutInterceptor.class); private static final ResourceBundle BUNDLE = BundleUtils.getBundle(JAXRSOutInterceptor.class); public JAXRSOutInterceptor() { super(Phase.MARSHAL); } public void handleMessage(Message message) { ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message); try { processResponse(providerFactory, message); } finally { ServerProviderFactory.releaseRequestState(providerFactory, message); } } @SuppressWarnings("resource") // Response shouldn't be closed here private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.isEmpty()) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response)responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo)exchange.get(OperationResourceInfo.class .getName()); serializeMessage(providerFactory, message, response, ori, true); } private int getStatus(Message message, int defaultValue) { Object customStatus = message.getExchange().get(Message.RESPONSE_CODE); return customStatus == null ? defaultValue : (Integer)customStatus; } private void serializeMessage(ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) { ResponseImpl response = (ResponseImpl)JAXRSUtils.copyResponseIfNeeded(theResponse); final Exchange exchange = message.getExchange(); boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod()); Object entity = response.getActualEntity(); if (headResponse && entity != null) { LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString()); entity = null; } Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke(); Annotation[] annotations = null; Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[]{}; Annotation[] responseAnns = response.getEntityAnnotations(); if (responseAnns != null) { annotations = new Annotation[staticAnns.length + responseAnns.length]; System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length); System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length); } else { annotations = staticAnns; } response.setStatus(getActualStatus(response.getStatus(), entity)); response.setEntity(entity, annotations); // Prepare the headers MultivaluedMap responseHeaders = prepareResponseHeaders(message, response, entity, firstTry); // Run the filters try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } // Write the entity entity = InjectionUtils.getEntity(response.getActualEntity()); setResponseStatus(message, getActualStatus(response.getStatus(), entity)); if (entity == null) { if (!headResponse) { responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0"); if (MessageUtils.getContextualBoolean(message, "remove.content.type.for.empty.response", false)) { responseHeaders.remove(HttpHeaders.CONTENT_TYPE); message.remove(Message.CONTENT_TYPE); } } HttpUtils.convertHeaderValuesToString(responseHeaders, true); return; } Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS); boolean ignoreWriters = ignoreWritersProp != null && Boolean.valueOf(ignoreWritersProp.toString()); if (ignoreWriters) { writeResponseToStream(message.getContent(OutputStream.class), entity); return; } MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE)); Class serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null; Class targetType = InjectionUtils.getRawResponseClass(entity); Type genericType = InjectionUtils.getGenericResponseType(invoked, serviceCls, response.getActualEntity(), targetType, exchange); targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType); annotations = response.getEntityAnnotations(); List writers = providerFactory .createMessageBodyWriterInterceptor(targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings()); OutputStream outOriginal = message.getContent(OutputStream.class); if (writers == null || writers.isEmpty()) { writeResponseErrorMessage(message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType); return; } try { boolean checkWriters = false; if (responseMediaType.isWildcardSubtype()) { Produces pM = AnnotationUtils.getMethodAnnotation(ori == null ? null : ori.getAnnotatedMethod(), Produces.class); Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class); checkWriters = pM == null && pC == null; } responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Response content type is: " + finalResponseContentType); } responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType); message.put(Message.CONTENT_TYPE, finalResponseContentType); boolean enabled = checkBufferingMode(message, writers, firstTry); try { try { JAXRSUtils.writeMessageBody(writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message); if (isResponseRedirected(message)) { return; } checkCachedStream(message, outOriginal, enabled); } finally { if (enabled) { OutputStream os = message.getContent(OutputStream.class); if (os != outOriginal && os instanceof CachedOutputStream) { os.close(); } message.setContent(OutputStream.class, outOriginal); message.put(XMLStreamWriter.class.getName(), null); } } } catch (Throwable ex) { logWriteError(firstTry, targetType, responseMediaType); handleWriteException(providerFactory, message, ex, firstTry); } } private MultivaluedMap prepareResponseHeaders(Message message, ResponseImpl response, Object entity, boolean firstTry) { MultivaluedMap responseHeaders = response.getMetadata(); @SuppressWarnings("unchecked") Map> userHeaders = (Map>)message.get(Message.PROTOCOL_HEADERS); if (firstTry && userHeaders != null) { responseHeaders.putAll(userHeaders); } if (entity != null) { Object customContentType = responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE); if (customContentType == null) { String initialResponseContentType = (String)message.get(Message.CONTENT_TYPE); if (initialResponseContentType != null) { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, initialResponseContentType); } } else { message.put(Message.CONTENT_TYPE, customContentType.toString()); } } message.put(Message.PROTOCOL_HEADERS, responseHeaders); setResponseDate(responseHeaders, firstTry); return responseHeaders; } private MediaType getResponseMediaType(Object mediaTypeHeader) { MediaType responseMediaType; if (mediaTypeHeader instanceof MediaType) { responseMediaType = (MediaType)mediaTypeHeader; } else { responseMediaType = mediaTypeHeader == null ? MediaType.WILDCARD_TYPE : JAXRSUtils.toMediaType(mediaTypeHeader.toString()); } return responseMediaType; } private int getActualStatus(int status, Object responseObj) { if (status == -1) { return responseObj == null ? 204 : 200; } return status; } private boolean checkBufferingMode(Message m, List writers, boolean firstTry) { if (!firstTry) { return false; } WriterInterceptor last = writers.get(writers.size() - 1); MessageBodyWriter w = ((WriterInterceptorMBW)last).getMBW(); Object outBuf = m.getContextualProperty(OUT_BUFFERING); boolean enabled = PropertyUtils.isTrue(outBuf); boolean configurableProvider = w instanceof AbstractConfigurableProvider; if (!enabled && outBuf == null && configurableProvider) { enabled = ((AbstractConfigurableProvider)w).getEnableBuffering(); } if (enabled) { boolean streamingOn = configurableProvider && ((AbstractConfigurableProvider)w).getEnableStreaming(); if (streamingOn) { m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter()); } else { m.setContent(OutputStream.class, new CachedOutputStream()); } } return enabled; } private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled) throws Exception { XMLStreamWriter writer = null; if (enabled) { writer = m.getContent(XMLStreamWriter.class); } else { writer = (XMLStreamWriter)m.get(XMLStreamWriter.class.getName()); } if (writer instanceof CachingXmlEventWriter) { CachingXmlEventWriter cache = (CachingXmlEventWriter)writer; if (cache.getEvents().size() != 0) { XMLStreamWriter origWriter = null; try { origWriter = StaxUtils.createXMLStreamWriter(osOriginal); for (XMLEvent event : cache.getEvents()) { StaxUtils.writeEvent(event, origWriter); } } finally { StaxUtils.close(origWriter); } } m.setContent(XMLStreamWriter.class, null); return; } if (enabled) { OutputStream os = m.getContent(OutputStream.class); if (os != osOriginal && os instanceof CachedOutputStream) { CachedOutputStream cos = (CachedOutputStream)os; if (cos.size() != 0) { cos.writeCacheTo(osOriginal); } } } } private void logWriteError(boolean firstTry, Class cls, MediaType ct) { if (firstTry) { JAXRSUtils.logMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, ct); } } private void handleWriteException(ServerProviderFactory pf, Message message, Throwable ex, boolean firstTry) { Response excResponse = null; if (firstTry) { excResponse = JAXRSUtils.convertFaultToResponse(ex, message); } else { message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE); } if (excResponse == null) { setResponseStatus(message, 500); throw new Fault(ex); } serializeMessage(pf, message, excResponse, null, false); } private void writeResponseErrorMessage(Message message, OutputStream out, String name, Class cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } } private MediaType checkFinalContentType(MediaType mt, List writers, boolean checkWriters) { if (checkWriters) { int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1; MessageBodyWriter writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW(); Produces pm = writer.getClass().getAnnotation(Produces.class); if (pm != null) { List sorted = JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM); mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0); } } if (mt.isWildcardType() || mt.isWildcardSubtype()) { if ("application".equals(mt.getType()) || mt.isWildcardType()) { mt = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { throw ExceptionUtils.toNotAcceptableException(null, null); } } return mt; } private void setResponseDate(MultivaluedMap headers, boolean firstTry) { if (!firstTry || headers.containsKey(HttpHeaders.DATE)) { return; } SimpleDateFormat format = HttpUtils.getHttpDateFormat(); headers.putSingle(HttpHeaders.DATE, format.format(new Date())); } private boolean isResponseAlreadyHandled(Message m) { return isResponseAlreadyCommited(m) || isResponseRedirected(m); } private boolean isResponseAlreadyCommited(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.RESPONSE_COMMITED)); } private boolean isResponseRedirected(Message m) { return Boolean.TRUE.equals(m.getExchange().get(AbstractHTTPDestination.REQUEST_REDIRECTED)); } private void writeResponseToStream(OutputStream os, Object responseObj) { try { byte[] bytes = responseObj.toString().getBytes(StandardCharsets.UTF_8); os.write(bytes, 0, bytes.length); } catch (Exception ex) { LOG.severe("Problem with writing the data to the output stream"); ex.printStackTrace(); throw new RuntimeException(ex); } } private void setResponseStatus(Message message, int status) { message.put(Message.RESPONSE_CODE, status); boolean responseHeadersCopied = isResponseHeadersCopied(message); if (responseHeadersCopied) { HttpServletResponse response = (HttpServletResponse)message.get(AbstractHTTPDestination.HTTP_RESPONSE); response.setStatus(status); } } // Some CXF interceptors such as FIStaxOutInterceptor will indirectly initiate // an early copying of response code and headers into the HttpServletResponse // TODO : Pushing the filter processing and copying response headers into say // PRE-LOGICAl and PREPARE_SEND interceptors will most likely be a good thing // however JAX-RS MessageBodyWriters are also allowed to add response headers // which is reason why a MultipartMap parameter in MessageBodyWriter.writeTo // method is modifiable. Thus we do need to know if the initial copy has already // occurred: for now we will just use to ensure the correct status is set private boolean isResponseHeadersCopied(Message message) { return PropertyUtils.isTrue(message.get(AbstractHTTPDestination.RESPONSE_HEADERS_COPIED)); } public void handleFault(Message message) { // complete } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 13134 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/interceptor/JAXRSOutInterceptor.java/#L73-L495 | 1 | 4824 | 13134 | minor |
| 1545 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JpegRewriter extends BinaryFileParser { private static final ByteOrder JPEG_BYTE_ORDER = ByteOrder.BIG_ENDIAN; private static final SegmentFilter EXIF_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isExifSegment(); } }; private static final SegmentFilter XMP_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isXmpSegment(); } }; private static final SegmentFilter PHOTOSHOP_APP13_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isPhotoshopApp13Segment(); } }; /** * Constructor. to guess whether a file contains an image based on its file * extension. */ public JpegRewriter() { setByteOrder(JPEG_BYTE_ORDER); } protected static class JFIFPieces { public final List pieces; public final List segmentPieces; public JFIFPieces(final List pieces, final List segmentPieces) { this.pieces = pieces; this.segmentPieces = segmentPieces; } } protected abstract static class JFIFPiece { protected abstract void write(OutputStream os) throws IOException; @Override public String toString() { return "[" + this.getClass().getName() + "]"; } } protected static class JFIFPieceSegment extends JFIFPiece { public final int marker; private final byte[] markerBytes; private final byte[] segmentLengthBytes; private final byte[] segmentData; public JFIFPieceSegment(final int marker, final byte[] segmentData) { this(marker, ByteConversions.toBytes((short) marker, JPEG_BYTE_ORDER), ByteConversions.toBytes((short) (segmentData.length + 2), JPEG_BYTE_ORDER), segmentData); } JFIFPieceSegment(final int marker, final byte[] markerBytes, final byte[] segmentLengthBytes, final byte[] segmentData) { this.marker = marker; this.markerBytes = markerBytes; this.segmentLengthBytes = segmentLengthBytes; this.segmentData = segmentData; // TODO clone? } @Override public String toString() { return "[" + this.getClass().getName() + " (0x" + Integer.toHexString(marker) + ")]"; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(segmentLengthBytes); os.write(segmentData); } public boolean isApp1Segment() { return marker == JpegConstants.JPEG_APP1_MARKER; } public boolean isAppSegment() { return marker >= JpegConstants.JPEG_APP0_MARKER && marker <= JpegConstants.JPEG_APP15_MARKER; } public boolean isExifSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.EXIF_IDENTIFIER_CODE)) { return false; } return true; } public boolean isPhotoshopApp13Segment() { if (marker != JpegConstants.JPEG_APP13_MARKER) { return false; } if (!new IptcParser().isPhotoshopJpegSegment(segmentData)) { return false; } return true; } public boolean isXmpSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.XMP_IDENTIFIER)) { return false; } return true; } public byte[] getSegmentData() { return segmentData; // TODO clone? } } static class JFIFPieceImageData extends JFIFPiece { private final byte[] markerBytes; private final byte[] imageData; JFIFPieceImageData(final byte[] markerBytes, final byte[] imageData) { super(); this.markerBytes = markerBytes; this.imageData = imageData; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(imageData); } } protected JFIFPieces analyzeJFIF(final ByteSource byteSource) throws ImageReadException, IOException { final List pieces = new ArrayList<>(); final List segmentPieces = new ArrayList<>(); final JpegUtils.Visitor visitor = new JpegUtils.Visitor() { // return false to exit before reading image data. @Override public boolean beginSOS() { return true; } @Override public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) { pieces.add(new JFIFPieceImageData(markerBytes, imageData)); } // return false to exit traversal. @Override public boolean visitSegment(final int marker, final byte[] markerBytes, final int segmentLength, final byte[] segmentLengthBytes, final byte[] segmentData) throws ImageReadException, IOException { final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); pieces.add(piece); segmentPieces.add(piece); return true; } }; new JpegUtils().traverseJFIF(byteSource, visitor); return new JFIFPieces(pieces, segmentPieces); } private interface SegmentFilter { boolean filter(JFIFPieceSegment segment); } protected List removeXmpSegments(final List segments) { return filterSegments(segments, XMP_SEGMENT_FILTER); } protected List removePhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER); } protected List findPhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER, true); } protected List removeExifSegments(final List segments) { return filterSegments(segments, EXIF_SEGMENT_FILTER); } protected List filterSegments(final List segments, final SegmentFilter filter) { return filterSegments(segments, filter, false); } protected List filterSegments(final List segments, final SegmentFilter filter, final boolean reverse) { final List result = new ArrayList<>(); for (final T piece : segments) { if (piece instanceof JFIFPieceSegment) { if (filter.filter((JFIFPieceSegment) piece) ^ !reverse) { result.add(piece); } } else if (!reverse) { result.add(piece); } } return result; } protected List insertBeforeFirstAppSegments( final List segments, final List newSegments) throws ImageWriteException { int firstAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { if (firstAppIndex == -1) { firstAppIndex = i; } } } final List result = new ArrayList(segments); if (firstAppIndex == -1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(firstAppIndex, newSegments); return result; } protected List insertAfterLastAppSegments( final List segments, final List newSegments) throws ImageWriteException { int lastAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { lastAppIndex = i; } } final List result = new ArrayList(segments); if (lastAppIndex == -1) { if (segments.size() < 1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(1, newSegments); } else { result.addAll(lastAppIndex + 1, newSegments); } return result; } protected void writeSegments(final OutputStream outputStream, final List segments) throws IOException { try (DataOutputStream os = new DataOutputStream(outputStream)) { JpegConstants.SOI.writeTo(os); for (final JFIFPiece piece : segments) { piece.write(os); } } } // private void writeSegment(OutputStream os, JFIFPieceSegment piece) // throws ImageWriteException, IOException // { // byte markerBytes[] = convertShortToByteArray(JPEG_APP1_MARKER, // JPEG_BYTE_ORDER); // if (piece.segmentData.length > 0xffff) // throw new JpegSegmentOverflowException("Jpeg segment is too long: " // + piece.segmentData.length); // int segmentLength = piece.segmentData.length + 2; // byte segmentLengthBytes[] = convertShortToByteArray(segmentLength, // JPEG_BYTE_ORDER); // // os.write(markerBytes); // os.write(segmentLengthBytes); // os.write(piece.segmentData); // } public static class JpegSegmentOverflowException extends ImageWriteException { private static final long serialVersionUID = -1062145751550646846L; public JpegSegmentOverflowException(final String message) { super(message); } } } |
blob | Long method | t | f | f | Long method | blob | 0 | 11250 | https://github.com/apache/commons-imaging/blob/fa7c16f434061d441d1c0d9dbcfd0f4c3092c880/src/main/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegRewriter.java/#L40-L353 | 1 | 1545 | 11250 | major |
| 139 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 1751 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 2 | 139 | 1751 | minor |
| 2660 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 15192 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 2 | 2660 | 15192 | minor |
| 2457 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions 4. Code duplication 5. Data class 6. Shotgun surgery 7. Speculative generality 8. Message chains 9. Temporary field 10. Data clumps 11. Primitive obsession 12. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
blob | Long method 2 Feature envy 3 Inconsistent naming conventions 4 Code duplication 5 Data class 6 Shotgun surgery 7 Speculative generality 8 Message chains 9 Temporary field | t | f | f | . Long method 2. Feature envy 3. Inconsistent naming conventions 4. Code duplication 5. Data class 6. Shotgun surgery 7. Speculative generality 8. Message chains 9. Temporary field | blob | 0 | 14527 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 2 | 2457 | 14527 | minor |
| 835 | LFOAbstractType YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 7750 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 2 | 835 | 7750 | major |
| 5763 | YES I found bad smells, the bad smells are: 1. Long method 2. Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
feature envy | Long method2 Data class | t | f | f | . Long method2. Data class | feature envy | 0 | 14545 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5763 | 14545 | major |
| 682 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | feature envy, long method | t | t | f | feature envy, long method | blob | 0 | 6594 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L3793-L3849 | 1 | 682 | 6594 | minor |
| 951 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Interrupted exception in catch block | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
data class | Long method2 Feature envy3 Interrupted exception in catch block | t | f | f | . Long method2. Feature envy3. Interrupted exception in catch block | data class | 0 | 8525 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 2 | 951 | 8525 | minor |
| 1807 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WireAdminImpl implements WireAdmin, ServiceListener { private BundleContext m_bundleContext; // A Map containing a service reference associated to a producer and a List // of wire objects private Map m_consumers = new HashMap(); /* ServiceReferences, List */ private Map m_producers = new HashMap(); /* ServiceReferences, List */ private List m_wires; // List containing the wires //private BindingController wireAdminListenersBindingController; // Filter corresponding to a consumer service private Filter m_consumerFilter; // Filter corresponding to a producer service private Filter m_producerFilter; // EventManager private EventManager m_eventManager; private static int m_wireCount = 0; private AsyncMethodCaller m_asyncMethodCaller = new AsyncMethodCaller(); //m_eventDispatcher.stop(); private static PrintStream m_traceout = null; private static PrintStream m_errorout = System.err; /** * Constructor with package visibility * * @param bundleContext the bundle context */ WireAdminImpl(BundleContext bundleContext) { m_bundleContext = bundleContext; if(bundleContext.getProperty("fr.imag.adele.wireadmin.trace") != null) { String value = bundleContext.getProperty("fr.imag.adele.wireadmin.trace"); if(value.equals("true")) { m_traceout = System.out; } } // Create the event manager (the event manager will start its own thread) m_eventManager = new EventManager(m_bundleContext); try { m_producerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Producer)"); m_consumerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Consumer)"); } catch (InvalidSyntaxException e) { // never thrown since LDAP expressions are correct } // Recover persistent wires getPersistentWires(); // Activate thread that does asynchronous calls to // the producersConnected and consummersConnected methods new Thread(m_asyncMethodCaller).start(); // Gets all producers and consumers that are present at the // moment the wire admin is created try { // Registration for events must be done first, as some service // can be registered during initialization m_bundleContext.addServiceListener(this,"(|"+m_producerFilter.toString()+m_consumerFilter.toString()+")"); // Replacement for the two following lines which work under OSCAR, // but not work under IBM's SMF //m_bundleContext.addServiceListener(this,m_consumerFilter.toString()); //m_bundleContext.addServiceListener(this,m_producerFilter.toString()); // Get all producers ServiceReference[] producerRefs = m_bundleContext.getServiceReferences(Producer.class.getName(),null); if(producerRefs!=null) { // lock the producers Map to avoid concurrent modifications due // to service events synchronized(m_producers) { for(int i=0;iWire object that connects a Producer * service to a Consumer service. * * The Producer service and Consumer service do not * have to be registered when the Wire object is created. * * The Wire configuration data must be persistently stored. * All Wire connections are reestablished when the * WireAdmin service is registered. * A Wire can be permanently removed by using the * {@link #deleteWire} method. * * The Wire object's properties must have case * insensitive String objects as keys (like the Framework). * However, the case of the key must be preserved. * The type of the value of the property must be one of the following: * * * type = basetype * | vector | arrays * * basetype = String | Integer | Long * | Float | Double | Byte * | Short | Character * | Boolean * * primitive = long | int | short * | char | byte | double | float * * arrays = primitive '[]' | basetype '[]' * * vector = Vector of basetype * * * The WireAdmin service must automatically add the * following Wire properties: * * * {@link WireConstants#WIREADMIN_PID} set to the value of the Wire object's * persistent identity (PID). This value is generated by the * Wire Admin service when a Wire object is created. * * * {@link WireConstants#WIREADMIN_PRODUCER_PID} set to the value of * Producer service's PID. * * * {@link WireConstants#WIREADMIN_CONSUMER_PID} set to the value of * Consumer service's PID. * * * If the properties argument * already contains any of these keys, then the supplied values * are replaced with the values assigned by the Wire Admin service. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_CREATED} * after the new Wire object becomes available from {@link #getWires}. * * @param producerPID The service.pid of the Producer service * to be connected to the Wire object. * @param consumerPID The service.pid of the Consumer service * to be connected to the Wire object. * @param properties The Wire object's properties. This argument may be null * if the caller does not wish to define any Wire object's properties. * @return The Wire object for this connection. * @throws java.lang.IllegalArgumentException If * properties contains case variants of the same key name. */ public Wire createWire(String producerPID, String consumerPID, Dictionary props) { ServiceReference producerServiceRef = null; ServiceReference consumerServiceRef = null; Dictionary properties; if(props == null) { properties = new Hashtable(); } else { //Clone the dictionary properties = cloneProperties(props); } // Addition of mandatory properties properties.put(WireConstants.WIREADMIN_CONSUMER_PID, consumerPID); properties.put(WireConstants.WIREADMIN_PRODUCER_PID, producerPID); properties.put(WireConstants.WIREADMIN_PID, generateWirePID()); // p.327 "Wire objects can be created when the producer or consumer // service is not registered WireImpl wire = new WireImpl(producerPID, consumerPID, properties); // Initialize the wire wire.initialize(m_bundleContext,m_eventManager); // Add the wire to the list synchronized(m_wires) { m_wires.add(wire); } // p. 357 "The Wire Admin service must broadcast a WireAdminEvent of // type WireAdminEvent.WIRE_CREATED after the new Wire object becomes // available from getWires(java.lang.String)." m_eventManager.fireEvent(WireAdminEvent.WIRE_CREATED,wire); synchronized (m_producers) { Iterator producerIterator = m_producers.keySet().iterator(); while(producerIterator.hasNext()) { producerServiceRef = (ServiceReference) producerIterator.next(); if (producerServiceRef.getProperty(Constants.SERVICE_PID).equals(producerPID)) { wire.bindProducer(producerServiceRef); break; } } } synchronized (m_consumers) { Iterator consumerIterator = m_consumers.keySet().iterator(); while(consumerIterator.hasNext()) { consumerServiceRef = (ServiceReference) consumerIterator.next(); if (consumerServiceRef.getProperty(Constants.SERVICE_PID).equals(consumerPID)) { wire.bindConsumer(consumerServiceRef); break; } } } // p.327 If both Producer and Consumer services are registered, they are // connected by the wire admin service. if(wire.isConnected()) { List wires = (List) m_producers.get(producerServiceRef); wires.add(wire); m_asyncMethodCaller.consumersConnected(wire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(consumerServiceRef); wires.add(wire); m_asyncMethodCaller.producersConnected(wire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // Newly created wires are immediately persisted to avoid information // loss in case of crashes. (spec not clear about this) persistWires(); return wire; } /** * Delete a Wire object. * * The Wire object representing a connection between * a Producer service and a Consumer service must be * removed. * The persistently stored configuration data for the Wire object * must destroyed. The Wire object's method {@link Wire#isValid} will return false * after it is deleted. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_DELETED} * after the Wire object becomes invalid. * * @param wire The Wire object which is to be deleted. */ public void deleteWire(Wire wire) { if(m_wires.contains(wire)) { WireImpl wireImpl = (WireImpl) wire; m_wires.remove(wire); if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } wireImpl.invalidate(); // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_DELETED,wireImpl); // Persist state to avoid losses in case of crashes (spec not clear about this). persistWires(); } else { traceln("WireAdminImpl: Cannot delete a wire that is not managed by this service"); } } /** * Update the properties of a Wire object. * * The persistently stored configuration data for the Wire object * is updated with the new properties and then the Consumer and Producer * services will be called at the respective {@link Consumer#producersConnected} * and {@link Producer#consumersConnected} methods. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_UPDATED} * after the updated properties are available from the Wire object. * * @param wire The Wire object which is to be updated. * @param properties The new Wire object's properties or null if no properties are required. */ public void updateWire(Wire wire, Dictionary props) { if(m_wires.contains(wire) == false) { traceln("WireAdminImpl: Cannot update a wire that is not managed by this service"); return; } // Clone the dictionary Dictionary properties = cloneProperties(props); // Put again the mandatory properties, in case they are not set properties.put(WireConstants.WIREADMIN_CONSUMER_PID,wire.getProperties().get(WireConstants.WIREADMIN_CONSUMER_PID)); properties.put(WireConstants.WIREADMIN_PRODUCER_PID,wire.getProperties().get(WireConstants.WIREADMIN_PRODUCER_PID)); properties.put(WireConstants.WIREADMIN_PID,wire.getProperties().get(WireConstants.WIREADMIN_PID)); WireImpl wireImpl = (WireImpl) wire; wireImpl.updateProperties(properties); // Call methods on Consumer and Producer if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_UPDATED,wireImpl); } /** * Return the Wire objects that match the given filter. * * The list of available Wire objects is matched against the * specified filter. Wire objects which match the * filter must be returned. These Wire objects are not necessarily * connected. The Wire Admin service should not return * invalid Wire objects, but it is possible that a Wire * object is deleted after it was placed in the list. * * The filter matches against the Wire object's properties including * {@link WireConstants#WIREADMIN_PRODUCER_PID}, {@link WireConstants#WIREADMIN_CONSUMER_PID} * and {@link WireConstants#WIREADMIN_PID}. * * @param filter Filter string to select Wire objects * or null to select all Wire objects. * @return An array of Wire objects which match the filter * or null if no Wire objects match the filter. * @throws org.osgi.framework.InvalidSyntaxException If the specified filter * has an invalid syntax. * @see org.osgi.framework.Filter */ public Wire[] getWires(String filter) throws InvalidSyntaxException { List res = null; if (filter == null) { return (Wire [])m_wires.toArray(new Wire[m_wires.size()]); } else { Filter tempFilter = m_bundleContext.createFilter(filter); Iterator iter = m_wires.iterator(); while (iter.hasNext()) { WireImpl currentWire = (WireImpl) iter.next(); if (tempFilter.match(currentWire.getProperties())) { if (res == null) { res = new ArrayList(); } res.add(currentWire); } } } if (res == null) { return null; } else { return (Wire [])res.toArray(new Wire[res.size()]); } } /** * listens Producer and Consumer services changes * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent) */ public void serviceChanged(ServiceEvent e) { ServiceReference serviceRef = e.getServiceReference(); // A consumer service changed if (m_consumerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("consumer registered"); List wires = new ArrayList(); synchronized(m_consumers) { m_consumers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived consumer currentWire.bindConsumer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.add(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } } } if(!called) { // P. 329 "If the Consumer service has no Wire objects attached when it // is registered, the WireAdmin service must always call producersConnected(null) m_asyncMethodCaller.producersConnected((Consumer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("consumer unregistering"); synchronized(m_consumers) { m_consumers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindConsumer(); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.remove(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } else { currentWire.unbindConsumer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to consumer service modification traceln("consumer service modified"); break; } } // Removed else to manage services which are both producers AND consumers if (m_producerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("producer registered"); List wires = new ArrayList(); synchronized(m_producers) { m_producers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived producer currentWire.bindProducer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.add(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } } } if(!called) { // P. 329 "If the Producer service has no Wire objects attached when it // is registered, the WireAdmin service must always call consumersConnected(null) m_asyncMethodCaller.consumersConnected((Producer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("Producer unregistering"); synchronized(m_producers) { m_producers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindProducer(); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.remove(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } else { currentWire.unbindProducer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to producer service modification traceln("producer service modified"); break; } } } /** * release all references before stop */ synchronized void releaseAll() { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.invalidate(); } Iterator producerIt = m_producers.keySet().iterator(); while (producerIt.hasNext()) { ServiceReference producerRef = (ServiceReference) producerIt.next(); ((Producer)m_bundleContext.getService(producerRef)).consumersConnected(null); } Iterator consumerIt = m_consumers.keySet().iterator(); while (consumerIt.hasNext()) { ServiceReference consumerRef = (ServiceReference) consumerIt.next(); ((Consumer)m_bundleContext.getService(consumerRef)).producersConnected(null); } // Stop the thread m_asyncMethodCaller.stop(); // Notify the event manager so that it stops its thread m_eventManager.stop(); persistWires(); } /** * This method generates a PID. The pid is generated from the bundle id, * a hash code from the current time and a counter. * * @return a wire PID */ private String generateWirePID() { Date d = new Date(); String PID="wire."+m_bundleContext.getBundle().getBundleId()+d.hashCode()+m_wireCount; m_wireCount ++; // Maybe the counter should go above 9? if(m_wireCount>9) { m_wireCount = 0; } return PID; } /** * Recover persistent wires * */ private void getPersistentWires() { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(m_bundleContext.getDataFile("wires.ser"))); m_wires = (ArrayList) ois.readObject(); ois.close(); if(m_wires!=null) { traceln("Deserialized "+m_wires.size()+" wires"); Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.initialize(m_bundleContext,m_eventManager); } } else { traceln("Couldn't Deserialize wires"); m_wires = new ArrayList(); } } catch(FileNotFoundException ex) { // do not show anything as this exception is thrown every // time the wire admin service is launched for the first // time m_wires = new ArrayList(); } catch(Exception ex) { trace(ex); m_wires = new ArrayList(); } } /** * Persist existing wires * */ private void persistWires() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(m_bundleContext.getDataFile("wires.ser"))); oos.writeObject(m_wires); oos.close(); traceln("Serialized "+m_wires.size()+" wires"); } catch(Exception ex) { trace(ex); } } /** * print an error * @param message message to error */ static void error(String message) { if (m_errorout != null) { m_errorout.println(message); } } /** * print a trace * @param message message to trace */ static void traceln(String message) { if (m_traceout != null) { trace(message); trace("\n"); } } /** * print a trace * @param message message to trace */ static void trace(String message) { if (m_traceout != null) { m_traceout.print(message); } } /** * print a trace * @param e exception to trace */ static void trace(Exception e) { if (m_traceout != null) { e.printStackTrace(m_traceout); } } /** * Clone a dictionary * * @param dictionary The dictionary to clone * @return a copy of the dicionary */ private Dictionary cloneProperties(Dictionary dictionary){ Dictionary properties=new Hashtable(); if (dictionary == null) { properties = new Hashtable(); } else { Enumeration enumeration=dictionary.keys(); while(enumeration.hasMoreElements()){ Object key=enumeration.nextElement(); Object value=dictionary.get(key); properties.put(key,value); } } return properties; } /** * This class enables calls to Producer.consumersConnected and Consumer.producersConnected * to be done asynchronously * * p.333 "The WireAdmin service can call the consumersConnected or producersConnected * methods during the registration of the consumer of producer service" * **/ class AsyncMethodCaller implements Runnable { private boolean m_stop = false; private List m_methodCallStack = new ArrayList(); public void run() { while (!m_stop) { Object nextTarget[] = null; synchronized (m_methodCallStack) { while (m_methodCallStack.size() == 0) { try { m_methodCallStack.wait(); } catch (InterruptedException ex) { // Ignore. } } nextTarget = (Object[]) m_methodCallStack.remove(0); } if(nextTarget[0] instanceof Producer) { try { ((Producer)nextTarget[0]).consumersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } // Removed else because nextTarget can be both producer and consumer if(nextTarget[0] instanceof Consumer) { try { ((Consumer)nextTarget[0]).producersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } } } /** * Place a call to Consumer.producersConnected on the stack * * @param c the consumer * @param wires the wires */ public void producersConnected(Consumer c,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{c,wires}); m_methodCallStack.notify(); } } /** * Place a call to Producer.consumersConnected on the stack * * @param p the producer * @param wires the wires */ public void consumersConnected(Producer p,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{p,wires}); m_methodCallStack.notify(); } } /** * stop the dispatcher * */ void stop() { m_stop = true; } } } |
blob | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 12042 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/wireadmin/src/main/java/org/apache/felix/wireadmin/WireAdminImpl.java/#L71-L1037 | 2 | 1807 | 12042 | critical |
| 2103 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | Long method | t | f | f | . Long method | feature envy | 0 | 13166 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 2 | 2103 | 13166 | minor |
| 1328 | YES I found bad smells The bad smells are: 1. Commented-out code 2. Inconsistent formatting 3. Long parameter list 4. Unnecessary constructors 5. Unnecessary use of "this" keyword 6. Inconsistent variable naming (e.g. "mainDexListCount" and "dexCount") 7. Magic numbers (e.g. "0" and "2" in @Config) 8. No clear purpose or functionality stated in class or methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | Commented-out code2 Inconsistent formatting3 Long parameter list4 Unnecessary constructors5 Unnecessary use of "this" keyword6 Inconsistent variable naming (eg "mainDexListCount" and "dexCount")7 Magic numbers (eg "0" and "2" in @Config)8 No clear purpose or functionality stated in class or methods | t | f | f | . Commented-out code2. Inconsistent formatting3. Long parameter list4. Unnecessary constructors5. Unnecessary use of "this" keyword6. Inconsistent variable naming (e.g. "mainDexListCount" and "dexCount")7. Magic numbers (e.g. "0" and "2" in @Config)8. No clear purpose or functionality stated in class or methods. | data class | 0 | 10705 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 2 | 1328 | 10705 | critical |
| 876 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
blob | Long method2 Feature envy 3 Duplicate code | t | f | f | . Long method2. Feature envy 3. Duplicate code | blob | 0 | 8010 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 2 | 876 | 8010 | minor |
| 4543 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Magic numbers 6. Primitive obsession 7. Nested conditional statements 8. Excessive use of comments 9. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
blob | Long method2 Feature envy 3 Duplicate code 4 Inconsistent naming conventions 5 Magic numbers 6 Primitive obsession 7 Nested conditional statements 8 Excessive use of comments 9 Incomplete error handling | t | f | f | . Long method2. Feature envy 3. Duplicate code 4. Inconsistent naming conventions 5. Magic numbers 6. Primitive obsession 7. Nested conditional statements 8. Excessive use of comments 9. Incomplete error handling | blob | 0 | 12066 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 2 | 4543 | 12066 | minor |
| 3842 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void transition(JobImpl job, JobEvent event) { job.addDiagnostic(((JobDiagnosticsUpdateEvent) event) .getDiagnosticUpdate()); } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9936 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java/#L2115-L2119 | 1 | 3842 | 9936 | minor |
| 1318 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | data class, long method | t | t | f | data class, long method | feature envy | 0 | 10692 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1318 | 10692 | major |
| 1405 | YES I found bad smells. the bad smells are: 1. No constructor provided for the Release class. 2. The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion. 3. The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future. 4. The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation. 5. The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | No constructor provided for the Release class2 The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion3 The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future4 The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation5 The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage | t | f | f | . No constructor provided for the Release class.2. The Release class only consists of getter methods and lacks any business logic, which could indicate a lack of cohesion.3. The fields in the Release class are all final, which could potentially limit flexibility and make it difficult to modify or extend the class in the future.4. The use of @Value annotation, which may indicate an overuse of Lombok and potentially hide the underlying code implementation.5. The lack of documentation or comments for the Release class, which could make it difficult for other developers to understand its purpose and usage. | data class | 0 | 10874 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 2 | 1405 | 10874 | major |
| 50 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRegistry public class ObjectFactory { /** * Create an instance of {@link LWM2M } * */ public LWM2M createLWM2M() { return new LWM2M(); } /** * Create an instance of {@link LWM2M.Object } * */ public LWM2M.Object createLWM2MObject() { return new LWM2M.Object(); } /** * Create an instance of {@link LWM2M.Object.Resources } * */ public LWM2M.Object.Resources createLWM2MObjectResources() { return new LWM2M.Object.Resources(); } /** * Create an instance of {@link LWM2M.Object.Resources.Item } * */ public LWM2M.Object.Resources.Item createLWM2MObjectResourcesItem() { return new LWM2M.Object.Resources.Item(); } } |
data class | long method | t | t | f | long method | data class | 0 | 866 | https://github.com/eclipse/vorto/blob/93919469e598ec07fed134536b901efd25cf674f/repository/repository-importer/importer-ipso/src/main/java/org/eclipse/vorto/repository/importer/ipso/ObjectFactory.java/#L37-L72 | 1 | 50 | 866 | major |
| 2102 | // bad smells are YES I found bad smells the bad smells are: 1. Hard coded values 2. Poor variable naming conventions (count, txid) 3. Public access modifiers for class and variable 4. No documentation or comments 5. No spacing or indentation 6. Underscore in class name 7. Incorrect indentation for class and variables 8. Inconsistent formatting 9. Unused import statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | Hard coded values 2 Poor variable naming conventions (count, txid) 3 Public access modifiers for class and variable 4 No documentation or comments 5 No spacing or indentation 6 Underscore in class name 7 Incorrect indentation for class and variables 8 Inconsistent formatting 9 Unused import statement | t | f | f | . Hard coded values 2. Poor variable naming conventions (count, txid) 3. Public access modifiers for class and variable 4. No documentation or comments 5. No spacing or indentation 6. Underscore in class name 7. Incorrect indentation for class and variables 8. Inconsistent formatting 9. Unused import statement | data class | 0 | 13161 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2102 | 13161 | minor |
| 702 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | data class | 0 | 6697 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 702 | 6697 | critical |
| 2684 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 15270 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 2684 | 15270 | minor |
| 20 | {"response": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 681 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 2 | 20 | 681 | minor |
| 2059 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | f | f | f | data class | 0 | 12962 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 2 | 2059 | 12962 | major | ||
| 1980 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 12638 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 1 | 1980 | 12638 | minor |
| 2648 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } } |
data class | long method, blob | t | t | f | long method, blob | data class | 0 | 15162 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 | 1 | 2648 | 15162 | minor |
| 1339 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class DFA28 extends DFA { public DFA28(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 28; this.eot = dfa_9; this.eof = dfa_21; this.min = dfa_10; this.max = dfa_11; this.accept = dfa_12; this.special = dfa_13; this.transition = dfa_14; } public String getDescription() { return "4005:2: ( rule__Object__UnorderedGroup_5__5 )?"; } public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_0 = input.LA(1); int index28_0 = input.index(); input.rewind(); s = -1; if ( LA28_0 == 19 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 0) ) {s = 1;} else if ( LA28_0 == 20 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 1) ) {s = 2;} else if ( LA28_0 == 21 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 2) ) {s = 3;} else if ( LA28_0 == 33 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 3) ) {s = 4;} else if ( LA28_0 == 26 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 5;} else if ( LA28_0 == 27 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 6;} else if ( LA28_0 == 22 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 5) ) {s = 7;} else if ( LA28_0 == 24 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 6) ) {s = 8;} else if ( LA28_0 == 25 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 7) ) {s = 9;} else if ( (LA28_0==EOF||LA28_0==17) ) {s = 10;} input.seek(index28_0); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 10738 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/ide/contentassist/antlr/internal/InternalBug304681TestLanguageParser.java/#L20062-L20120 | 2 | 1339 | 10738 | major |
| 400 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class CoordActionQueryExecutor extends QueryExecutor { public enum CoordActionQuery { UPDATE_COORD_ACTION, UPDATE_COORD_ACTION_STATUS_PENDING_TIME, UPDATE_COORD_ACTION_FOR_INPUTCHECK, UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK, UPDATE_COORD_ACTION_DEPENDENCIES, UPDATE_COORD_ACTION_FOR_START, UPDATE_COORD_ACTION_FOR_MODIFIED_DATE, UPDATE_COORD_ACTION_RERUN, GET_COORD_ACTION, GET_COORD_ACTION_STATUS, GET_COORD_ACTIVE_ACTIONS_COUNT_BY_JOBID, GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME, GET_COORD_ACTIONS_STATUS_UNIGNORED, GET_COORD_ACTIONS_PENDING_COUNT, GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE, GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE, GET_TERMINATED_ACTIONS_FOR_DATES, GET_TERMINATED_ACTION_IDS_FOR_DATES, GET_ACTIVE_ACTIONS_FOR_DATES, GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN, GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN, GET_COORD_ACTION_FOR_SLA, GET_COORD_ACTION_FOR_INPUTCHECK }; private static CoordActionQueryExecutor instance = new CoordActionQueryExecutor(); private CoordActionQueryExecutor() { } public static QueryExecutor getInstance() { return CoordActionQueryExecutor.instance; } @Override public Query getUpdateQuery(CoordActionQuery namedQuery, CoordinatorActionBean actionBean, EntityManager em) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); switch (namedQuery) { case UPDATE_COORD_ACTION: query.setParameter("actionNumber", actionBean.getActionNumber()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("consoleUrl", actionBean.getConsoleUrl()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("timeOut", actionBean.getTimeOut()); query.setParameter("trackerUri", actionBean.getTrackerUri()); query.setParameter("type", actionBean.getType()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("jobId", actionBean.getJobId()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("nominalTime", actionBean.getNominalTimestamp()); query.setParameter("slaXml", actionBean.getSlaXmlBlob()); query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_STATUS_PENDING_TIME: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("pending", actionBean.getPending()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_DEPENDENCIES: query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_START: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("pending", actionBean.getPending()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_MODIFIED_DATE: query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_RERUN: query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("status", actionBean.getStatusStr()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("rerunTime", actionBean.getRerunTimestamp()); query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + namedQuery.name()); } return query; } @Override public Query getSelectQuery(CoordActionQuery namedQuery, EntityManager em, Object... parameters) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); CoordActionQuery caQuery = (CoordActionQuery) namedQuery; switch (caQuery) { case GET_COORD_ACTION: case GET_COORD_ACTION_STATUS: case GET_COORD_ACTION_FOR_SLA: case GET_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("id", parameters[0]); break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: query.setParameter("jobId", parameters[0]); break; case GET_COORD_ACTIONS_PENDING_COUNT: query.setParameter("jobId", parameters[0]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: query.setParameter("ids", parameters[0]); break; case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: query.setParameter("jobId", parameters[0]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: case GET_TERMINATED_ACTION_IDS_FOR_DATES: case GET_ACTIVE_ACTIONS_FOR_DATES: query.setParameter("jobId", parameters[0]); query.setParameter("startTime", new Timestamp(((Date) parameters[1]).getTime())); query.setParameter("endTime", new Timestamp(((Date) parameters[2]).getTime())); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); query.setParameter("currentTime", new Timestamp(new Date().getTime())); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + caQuery.name()); } return query; } @Override public int executeUpdate(CoordActionQuery namedQuery, CoordinatorActionBean jobBean) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getUpdateQuery(namedQuery, jobBean, em); int ret = jpaService.executeUpdate(namedQuery.name(), query, em); return ret; } @Override public CoordinatorActionBean get(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { CoordinatorActionBean bean = getIfExist(namedQuery, parameters); if (bean == null) { throw new JPAExecutorException(ErrorCode.E0605, getSelectQuery(namedQuery, Services.get().get(JPAService.class).getEntityManager(), parameters).toString()); } return bean; } @Override public CoordinatorActionBean getIfExist(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { return null; } CoordinatorActionBean bean = constructBean(namedQuery, ret); return bean; } @Override public List getList(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); List retList = (List) jpaService.executeGetList(namedQuery.name(), query, em); List beanList = new ArrayList(); if (retList != null) { for (Object ret : retList) { beanList.add(constructBean(namedQuery, ret)); } } return beanList; } private CoordinatorActionBean constructBean(CoordActionQuery namedQuery, Object ret) throws JPAExecutorException { CoordinatorActionBean bean; Object[] arr; switch (namedQuery) { case GET_COORD_ACTION: bean = (CoordinatorActionBean) ret; break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: bean = new CoordinatorActionBean(); bean.setJobId((String) ret); break; case GET_COORD_ACTION_STATUS: bean = new CoordinatorActionBean(); bean.setStatusStr((String)ret); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setStatusStr((String)arr[0]); bean.setPending((Integer)arr[1]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setNominalTime((Timestamp)arr[1]); bean.setCreatedTime((Timestamp)arr[2]); bean.setActionXmlBlob((StringBlob)arr[3]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: bean = (CoordinatorActionBean) ret; break; case GET_TERMINATED_ACTION_IDS_FOR_DATES: bean = new CoordinatorActionBean(); bean.setId((String) ret); break; case GET_ACTIVE_ACTIONS_FOR_DATES: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); bean.setNominalTime((Timestamp) arr[5]); bean.setCreatedTime((Timestamp) arr[6]); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPushMissingDependenciesBlob((StringBlob) arr[4]); break; case GET_COORD_ACTION_FOR_SLA: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setJobId((String) arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setLastModifiedTime((Timestamp) arr[4]); break; case GET_COORD_ACTION_FOR_INPUTCHECK: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setActionNumber((Integer) arr[1]); bean.setJobId((String) arr[2]); bean.setStatus(CoordinatorAction.Status.valueOf((String) arr[3])); bean.setRunConfBlob((StringBlob) arr[4]); bean.setNominalTime(DateUtils.toDate((Timestamp) arr[5])); bean.setCreatedTime(DateUtils.toDate((Timestamp) arr[6])); bean.setActionXmlBlob((StringBlob) arr[7]); bean.setMissingDependenciesBlob((StringBlob) arr[8]); bean.setPushMissingDependenciesBlob((StringBlob) arr[9]); bean.setTimeOut((Integer) arr[10]); bean.setExternalId((String) arr[11]); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot construct action bean for " + namedQuery.name()); } return bean; } @Override public Object getSingleValue(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { throw new JPAExecutorException(ErrorCode.E0604, query.toString()); } return ret; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 4082 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/executor/jpa/CoordActionQueryExecutor.java/#L40-L383 | 2 | 400 | 4082 | major |
| 4095 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } } |
blob | long method | t | t | f | long method | blob | 0 | 10789 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 | 1 | 4095 | 10789 | minor |
| 1423 | {"output":"YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
blob | t | f | f | blob | 0 | 10933 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 1423 | 10933 | major | ||
| 187 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long method", "Duplicate code", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
data class | long method, duplicate code, feature envy | t | t | f | long method, duplicate code, feature envy | data class | 0 | 2120 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 187 | 2120 | major |
| 325 | YES, I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class WebServer { public static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private HttpServer2 httpServer; private final HasConfig conf; private InetSocketAddress httpAddress; private InetSocketAddress httpsAddress; protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver"; public WebServer(HasConfig conf) { this.conf = conf; } public HasConfig getConf() { return conf; } private void init() { final String pathSpec = "/has/v1/*"; // add has packages httpServer.addJerseyResourcePackage(AsRequestApi.class .getPackage().getName(), pathSpec); } public void defineFilter() { String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType.equals("kerberos")) { // add authentication filter for webhdfs final String className = conf.getString( WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY, WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT); final String name = className; Map params = getAuthFilterParams(conf); String kadminPathSpec = "/has/v1/kadmin/*"; String hadminPathSpec = "/has/v1/hadmin/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className, params, new String[]{kadminPathSpec, hadminPathSpec}); HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className + ")"); } } public void defineConfFilter() { String confFilterName = ConfFilter.class.getName(); String confPath = "/has/v1/conf/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName, getAuthFilterParams(conf), new String[]{confPath}); HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName + ")"); } private Map getAuthFilterParams(HasConfig conf) { Map params = new HashMap<>(); String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType != null && !authType.isEmpty()) { params.put(AuthenticationFilter.AUTH_TYPE, authType); } String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY); if (principal != null && !principal.isEmpty()) { try { principal = SecurityUtil.getServerPrincipal(principal, getHttpsAddress().getHostName()); } catch (IOException e) { LOG.warn("Errors occurred when get server principal. " + e.getMessage()); } params.put(KerberosAuthenticationHandler.PRINCIPAL, principal); } String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY); if (keytab != null && !keytab.isEmpty()) { params.put(KerberosAuthenticationHandler.KEYTAB, keytab); } String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES); if (rule != null && !rule.isEmpty()) { params.put(KerberosAuthenticationHandler.NAME_RULES, rule); } else { params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT"); } return params; } public InetSocketAddress getBindAddress() { if (httpAddress != null) { return httpAddress; } else if (httpsAddress != null) { return httpsAddress; } else { return null; } } /** * for information related to the different configuration options and * Http Policy is decided. * * @throws HasException HAS exception when starting web server */ public void start() throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); final String bindHost = conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY); InetSocketAddress httpAddr = null; if (policy.isHttpEnabled()) { final String httpAddrString = conf.getString( WebConfigKey.HAS_HTTP_ADDRESS_KEY, WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT); httpAddr = NetUtils.createSocketAddr(httpAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort()); } LOG.info("Get the http address: " + httpAddr); } InetSocketAddress httpsAddr = null; if (policy.isHttpsEnabled()) { final String httpsAddrString = conf.getString( WebConfigKey.HAS_HTTPS_ADDRESS_KEY, WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT); httpsAddr = NetUtils.createSocketAddr(httpsAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort()); } LOG.info("Get the https address: " + httpsAddr); } HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has"); try { httpServer = builder.build(); } catch (IOException e) { throw new HasException("Errors occurred when building http server. " + e.getMessage()); } init(); try { httpServer.start(); } catch (IOException e) { throw new HasException("Errors occurred when starting http server. " + e.getMessage()); } int connIdx = 0; if (policy.isHttpEnabled()) { httpAddress = httpServer.getConnectorAddress(connIdx++); if (httpAddress != null) { conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, NetUtils.getHostPortString(httpAddress)); } } if (policy.isHttpsEnabled()) { httpsAddress = httpServer.getConnectorAddress(connIdx); if (httpsAddress != null) { conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, NetUtils.getHostPortString(httpsAddress)); } } } public void setWebServerAttribute(HasServer hasServer) { httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer); } public static HasServer getHasServerFromContext(ServletContext context) { return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY); } /** * Get http policy. * * @param conf the HAS config * @return HttpConfig.Policy the policy */ public HttpConfig.Policy getHttpPolicy(HasConfig conf) { String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY, WebConfigKey.HAS_HTTP_POLICY_DEFAULT); HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr); if (policy == null) { throw new HadoopIllegalArgumentException("Unrecognized value '" + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY); } conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name()); return policy; } /** * Return a HttpServer.Builder that the HAS can use to * initialize their HTTP / HTTPS server. * * @param conf the HAS config * @param httpAddr the InetSocketAddress of http * @param httpsAddr the InetSocketAddress of https * @param name the host name * @return HttpServer2.Builder the builder * @throws HasException HAS exception */ public HttpServer2.Builder httpServerTemplateForHAS( HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name) throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); HttpServer2.Builder builder = new HttpServer2.Builder().setName(name); if (policy.isHttpEnabled()) { if (httpAddr != null && httpAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } if (policy.isHttpsEnabled() && httpsAddr != null) { HasConfig sslConf = loadSslConfiguration(conf); loadSslConfToHttpServerBuilder(builder, sslConf); if (httpsAddr != null && httpsAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } return builder; } /** * Load HTTPS-related configuration. * * @param conf HAS config * @return HasConfig after loading ssl configuration * @throws HasException HAS exception when loading HTTPS related configuration */ public HasConfig loadSslConfiguration(HasConfig conf) throws HasException { HasConfig sslConf = new HasConfig(); String sslConfigString = conf.getString( WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT); LOG.info("Get the ssl config file: " + sslConfigString); File sslConfig = new File(sslConfigString); if (!sslConfig.exists()) { throw new HasException("The ssl server config file " + sslConfigString + " does not exist."); } try { sslConf.addIniConfig(sslConfig); } catch (IOException e) { throw new HasException("Errors occurred when adding config. " + e.getMessage()); } final String[] reqSslProps = { WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY }; // Check if the required properties are included for (String sslProp : reqSslProps) { if (sslConf.getString(sslProp) == null) { LOG.warn("SSL config " + sslProp + " is missing. If " + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY + " is specified, make sure it is a relative path"); } } boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT); sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth); return sslConf; } public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder, HasConfig sslConf) { return builder .needsClientAuth( sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT)) .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY)) .keyStore(sslConf.getString("ssl.server.keystore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.keystore.type", "jks")) .trustStore(sslConf.getString("ssl.server.truststore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.truststore.type", "jks")) .excludeCiphers( sslConf.getString("ssl.server.exclude.cipher.list")); } /** * Leverages the Configuration.getPassword method to attempt to get * passwords from the CredentialProvider API before falling back to * clear text in config - if falling back is allowed. * * @param conf Configuration instance * @param alias name of the credential to retreive * @return String credential value or null */ public String getPassword(HasConfig conf, String alias) { return conf.getString(alias); } public void stop() throws Exception { if (httpServer != null) { httpServer.stop(); } } public InetSocketAddress getHttpAddress() { return httpAddress; } public InetSocketAddress getHttpsAddress() { return httpsAddress; } } |
blob | Feature envy, 2Long method | t | f | f | .Feature envy, 2.Long method | blob | 0 | 3358 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java/#L43-L374 | 2 | 325 | 3358 | major |
| 1254 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 10475 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 2 | 1254 | 10475 | minor |
| 2464 | YES I found bad smells: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 14556 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 2 | 2464 | 14556 | major |
| 3638 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 8239 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xtext.ui.examples/projects/domainmodel/org.eclipse.xtext.example.domainmodel.ide/src-gen/org/eclipse/xtext/example/domainmodel/ide/contentassist/antlr/internal/InternalDomainmodelParser.java/#L62002-L62027 | 1 | 3638 | 8239 | minor | ||
| 1270 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 10566 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1270 | 10566 | major |
| 1704 | public static class NotificationsService { private final NotificationsAggregatorState state;-------------- YES I found bad smells the bad smells are: 1. Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2. Encapsulation violation (direct access to the state variable instead of using a getter) 3. Lack of modularity (actions and state are contained within a single class) 4. Lack of proper commenting/documentation 5. Violation of the single responsibility principle (class is performing too many tasks) 6. Violation of the open-closed principle (class is not easily extensible) 7. Lack of proper formatting and indentation 8. Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9. Potential thread-unsafe access to variables (depending on the context and usage of the class) 10. Lack of exception handling 11. Potential code duplication (if similar functionality is implemented elsewhere) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2 Encapsulation violation (direct access to the state variable instead of using a getter) 3 Lack of modularity (actions and state are contained within a single class) 4 Lack of proper commenting/documentation 5 Violation of the single responsibility principle (class is performing too many tasks) 6 Violation of the open-closed principle (class is not easily extensible) 7 Lack of proper formatting and indentation 8 Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9 Potential thread-unsafe access to variables (depending on the context and usage of the class) | t | f | f | . Undescriptive and unclear class names (NotificationsAggregatorState and NotificationsService) 2. Encapsulation violation (direct access to the state variable instead of using a getter) 3. Lack of modularity (actions and state are contained within a single class) 4. Lack of proper commenting/documentation 5. Violation of the single responsibility principle (class is performing too many tasks) 6. Violation of the open-closed principle (class is not easily extensible) 7. Lack of proper formatting and indentation 8. Unclear and inconsistent variable naming (recentEventLogsCount and activeRequestsCount) 9. Potential thread-unsafe access to variables (depending on the context and usage of the class) | data class | 0 | 11741 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 1704 | 11741 | minor |
| 564 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 5711 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 2 | 564 | 5711 | minor |
| 2223 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 13567 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 1 | 2223 | 13567 | major |
| 1893 | //(=> //{BinaryLogicalExpression.lhs=current} public Group getGroup_1_0_0() { return cGroup_1_0_0; } YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | _0_0() { return cGroup_ | t | f | f | _0_0() { return cGroup_ | data class | 0 | 12320 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 2 | 1893 | 12320 | minor |
| 76 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(ListBootVolumeAttachmentsResponse o) { opcNextPage(o.getOpcNextPage()); opcRequestId(o.getOpcRequestId()); items(o.getItems()); return this; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1158 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-core/src/main/java/com/oracle/bmc/core/responses/ListBootVolumeAttachmentsResponse.java/#L33-L45 | 2 | 76 | 1158 | major |
| 2186 | { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13435 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 1 | 2186 | 13435 | major |
| 573 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 5757 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 573 | 5757 | critical |
| 286 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 3056 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 286 | 3056 | major |
| 822 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7701 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 2 | 822 | 7701 | major |
| 1825 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 12107 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L6091-L6111 | 2 | 1825 | 12107 | minor | ||
| 215 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } } |
blob | data class | t | t | f | data class | blob | 0 | 2326 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 | 1 | 215 | 2326 | major |
| 3413 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private @Metrics(context="metricssystem") public class MetricsSystemImpl extends MetricsSystem implements MetricsSource { static final Log LOG = LogFactory.getLog(MetricsSystemImpl.class); static final String MS_NAME = "MetricsSystem"; static final String MS_STATS_NAME = MS_NAME +",sub=Stats"; static final String MS_STATS_DESC = "Metrics system metrics"; static final String MS_CONTROL_NAME = MS_NAME +",sub=Control"; static final String MS_INIT_MODE_KEY = "hadoop.metrics.init.mode"; enum InitMode { NORMAL, STANDBY } private final Map sources; private final Map allSources; private final Map sinks; private final Map allSinks; private final List callbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private int period; // seconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.info(this.prefix +" metrics system started (again)"); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.info(prefix +" metrics system started in standby mode"); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.info(prefix +" metrics system started"); for (Callback cb : callbacks) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.info(prefix +" metrics system stopped (again)"); return; } for (Callback cb : callbacks) cb.preStop(); LOG.info("Stopping "+ prefix +" metrics system..."); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.info(prefix +" metrics system stopped."); for (Callback cb : callbacks) cb.postStop(); } @Override public synchronized T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { LOG.warn("Sink "+ name +" already exists!"); return sink; } allSinks.put(name, sink); if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); sa.start(); LOG.info("Registered sink "+ name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance( callback.getClass().getClassLoader(), new Class[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback "+ method.getName(), e); } return null; } })); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.save(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period * 1000; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn(e); } } }, millis, millis); LOG.info("Scheduled snapshot period at "+ period +" second(s)."); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.now(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.now() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.now(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.now() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); int confPeriod = 0; for (Entry entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); confPeriod = confPeriod == 0 ? sinkPeriod : ArithmeticUtils.gcd(confPeriod, sinkPeriod); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } period = confPeriod > 0 ? confPeriod : config.getInt(PERIOD_KEY, PERIOD_DEFAULT); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT), conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.info(prefix +" metrics system shutdown complete."); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf((m2 == null ? InitMode.NORMAL.name() : m2) .toUpperCase(Locale.US)); } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 6664 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java/#L69-L601 | 2 | 3413 | 6664 | major |
| 475 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | blob | t | t | f | blob | data class | 0 | 4581 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 1 | 475 | 4581 | minor |
| 4098 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CommandShelvesets extends Command { private static final String SHELVESETS_ELEMENT_NAME = "shelvesets"; //$NON-NLS-1$ /** * The default long format for the current locale. */ private final DateFormat defaultFormat = SimpleDateFormat.getDateTimeInstance(); public CommandShelvesets() { super(); } @Override public void run() throws ArgumentException, MalformedURLException, CLCException, LicenseException, InputValidationException { if (getFreeArguments().length > 1) { final String messageFormat = Messages.getString("CommandShelvesets.CommandRequiresZeroOrOneShelvesetNamesFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getCanonicalName()); throw new InvalidFreeArgumentException(message); } String ownerArg = null; String format = OptionFormat.BRIEF; Option o = null; if ((o = findOptionType(OptionFormat.class)) != null) { format = ((OptionFormat) o).getValue(); } if ((o = findOptionType(OptionOwner.class)) != null) { ownerArg = ((OptionOwner) o).getValue(); } /* * Pass an empty array of local paths because none of the free arguments * is a local path for this command. */ final TFSTeamProjectCollection connection = createConnection(new String[0]); final VersionControlClient client = connection.getVersionControlClient(); initializeClient(client); final Workspace workspace = realizeCachedWorkspace(determineCachedWorkspace(new String[0]), client); Check.notNull(workspace, "workspace"); //$NON-NLS-1$ String shelvesetName = null; String shelvesetOwner = null; if (getFreeArguments().length == 1) { final WorkspaceSpec spec = WorkspaceSpec.parse(getFreeArguments()[0], VersionControlConstants.AUTHENTICATED_USER); shelvesetName = spec.getName(); shelvesetOwner = spec.getOwner(); if (shelvesetName.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetName = null; } } if (ownerArg != null) { shelvesetOwner = ownerArg; } if (shelvesetOwner == null) { shelvesetOwner = VersionControlConstants.AUTHENTICATED_USER; } else if (shelvesetOwner.equalsIgnoreCase("*")) //$NON-NLS-1$ { shelvesetOwner = null; } final Shelveset[] shelvesets = client.queryShelvesets(shelvesetName, shelvesetOwner, null); if (shelvesets.length == 0) { final String displayOwner = (shelvesetOwner != null && shelvesetOwner.equals(VersionControlConstants.AUTHENTICATED_USER)) ? connection.getAuthorizedIdentity().getDisplayName() : ((shelvesetOwner == null) ? "*" : shelvesetOwner); //$NON-NLS-1$ final String displayShelvesetName = (shelvesetName == null) ? "*" : shelvesetName; //$NON-NLS-1$ final String shelvesetPattern = new WorkspaceSpec(displayShelvesetName, displayOwner).toString(); final String messageFormat = Messages.getString("CommandShelvesets.NoShelvesetsFoundMatchingFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, shelvesetPattern); if (shelvesetName == null) { getDisplay().printLine(message); setExitCode(ExitCode.PARTIAL_SUCCESS); return; } throw new InvalidFreeArgumentException(message); } Arrays.sort(shelvesets, ShelvesetComparator.INSTANCE); if (OptionFormat.DETAILED.equalsIgnoreCase(format)) { ShelvesetPrinter.printDetailedShelvesets( shelvesets, defaultFormat, getDisplay(), connection.getWorkItemClient()); } else if (OptionFormat.BRIEF.equalsIgnoreCase(format)) { ShelvesetPrinter.printBriefShelvesets(shelvesets, getDisplay()); } else if (OptionFormat.XML.equalsIgnoreCase(format)) { ShelvesetPrinter.printXMLShelvesets(shelvesets, SHELVESETS_ELEMENT_NAME, getDisplay()); } else { final String messageFormat = Messages.getString("CommandShelvesets.UnsupportedOutputFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, format); throw new RuntimeException(message); } } @Override public AcceptedOptionSet[] getSupportedOptionSets() { final AcceptedOptionSet[] optionSets = new AcceptedOptionSet[1]; optionSets[0] = new AcceptedOptionSet(new Class[] { OptionOwner.class, OptionFormat.class }, "[]"); //$NON-NLS-1$ return optionSets; } @Override public String[] getCommandHelpText() { return new String[] { Messages.getString("CommandShelvesets.HelpText1") //$NON-NLS-1$ }; } } |
blob | long method | t | t | f | long method | blob | 0 | 10793 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/commands/CommandShelvesets.java/#L34-L171 | 1 | 4098 | 10793 | minor |
| 1066 | {"message": "YES I found bad smells the bad smells are: 1. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
blob | 1. data class | t | t | f | 1. data class | blob | 0 | 9581 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1066 | 9581 | minor |
| 1638 | -if you notice none or no bad smells--*/ NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 11532 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 2 | 1638 | 11532 | major | ||
| 1146 | { "message": "YES I found bad smells" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
blob | Not specified | f | f | f | "YES I found bad smells" } | false | 0 | 10114 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 2 | 1146 | 10114 | critical |
| 292 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } } |
data class | long method | t | t | f | long method | data class | 0 | 3077 | https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 | 1 | 292 | 3077 | critical |
| 3763 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class CurrentCreationalContext { private final ThreadLocal> creationalContext = new ThreadLocal>(); public CreationalContext get() { return creationalContext.get(); } public void set(CreationalContext value) { creationalContext.set(value); } public void remove() { creationalContext.remove(); } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 9405 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/cdi/CurrentCreationalContext.java/#L24-L38 | 2 | 3763 | 9405 | minor |
| 166 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({"rawtypes", "unchecked"}) public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler { protected final JMXAgentContext agentContext; protected StandardMBean mbean; protected final AtomicLong trackedId = new AtomicLong(); /** * * @param agentContext * @param filter */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) { super(agentContext.getBundleContext(), filter, null); this.agentContext = agentContext; } /** * * @param agentContext * @param clazz */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) { super(agentContext.getBundleContext(), clazz, null); this.agentContext = agentContext; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Logger logger = agentContext.getLogger(); Object trackedService = null; long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); //API stipulates versions for compendium services with static ObjectName //This shouldn't happen but added as a consistency check if (trackedId.compareAndSet(0, serviceId)) { logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceId + "]"); trackedService = context.getService(reference); mbean = constructInjectMBean(trackedService); agentContext.registerMBean(AbstractCompendiumHandler.this); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed"); } return trackedService; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { Logger logger = agentContext.getLogger(); long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID); if (trackedId.compareAndSet(serviceID, 0)) { logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceID + "]"); agentContext.unregisterMBean(AbstractCompendiumHandler.this); context.ungetService(reference); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed"); } } private String getServiceDescription(ServiceReference reference) { String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION); if (serviceDescription == null) { Object obj = reference.getProperty(Constants.OBJECTCLASS); if (obj instanceof String[]) { StringBuilder sb = new StringBuilder(); for (String s : (String[]) obj) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } serviceDescription = sb.toString(); } else { serviceDescription = obj.toString(); } } return serviceDescription; } /** * Gets the StandardMBean managed by this handler when the backing service is available or null * * @see org.apache.aries.jmx.MBeanHandler#getMbean() */ public StandardMBean getMbean() { return mbean; } /** * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied * service tracked by this handler * * @param targetService * the compendium service tracked by this handler * @return The StandardMBean instance whose registration lifecycle will be managed by this handler */ protected abstract StandardMBean constructInjectMBean(Object targetService); /** * The base name of the MBean. Will be expanded with the framework name and the UUID. * @return */ protected abstract String getBaseName(); /** * @see org.apache.aries.jmx.MBeanHandler#getName() */ public String getName() { return ObjectNameUtils.createFullObjectName(context, getBaseName()); } } |
blob | data class | t | t | f | data class | blob | 0 | 2010 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java/#L43-L166 | 1 | 166 | 2010 | minor |
| 1470 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Comments describing things that should be implemented or fixed 6. Inconsistent formatting and indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } } |
blob | Long method 2 Feature envy 3 Duplicate code 4 Magic numbers 5 Comments describing things that should be implemented or fixed 6 Inconsistent formatting and indentation | t | f | f | . Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Comments describing things that should be implemented or fixed 6. Inconsistent formatting and indentation | blob | 0 | 11048 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 | 2 | 1470 | 11048 | minor |
| 3200 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 4807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 1 | 3200 | 4807 | minor | ||
| 196 | {"message": "YES I found bad smells"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MissedUpdatesFinder extends MissedUpdatesFinderBase { private long ourHighThreshold; // 80th percentile private long ourHighest; // currently just used for logging/debugging purposes private String logPrefix; private long nUpdates; MissedUpdatesFinder(List ourUpdates, String logPrefix, long nUpdates, long ourLowThreshold, long ourHighThreshold) { super(ourUpdates, ourLowThreshold); this.logPrefix = logPrefix; this.ourHighThreshold = ourHighThreshold; this.ourHighest = ourUpdates.get(0); this.nUpdates = nUpdates; } public MissedUpdatesRequest find(List otherVersions, Object updateFrom, Supplier canHandleVersionRanges) { otherVersions.sort(absComparator); if (debug) { log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom); } long otherHigh = percentile(otherVersions, .2f); long otherLow = percentile(otherVersions, .8f); long otherHighest = otherVersions.get(0); if (ourHighThreshold < otherLow) { // Small overlap between version windows and ours is older // This means that we might miss updates if we attempted to use this method. // Since there exists just one replica that is so much newer, we must // fail the sync. log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (ourLowThreshold > otherHigh && ourHighest >= otherHighest) { // Small overlap between windows and ours is newer. // Using this list to sync would result in requesting/replaying results we don't need // and possibly bringing deleted docs back to life. log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); // Because our versions are newer, IndexFingerprint with the remote would not match us. // We return true on our side, but the remote peersync with us should fail. return MissedUpdatesRequest.ALREADY_IN_SYNC; } boolean completeList = otherVersions.size() < nUpdates; MissedUpdatesRequest updatesRequest; if (canHandleVersionRanges.get()) { updatesRequest = handleVersionsWithRanges(otherVersions, completeList); } else { updatesRequest = handleIndividualVersions(otherVersions, completeList); } if (updatesRequest.totalRequestedUpdates > nUpdates) { log.info("{} PeerSync will fail because number of missed updates is more than:{}", logPrefix, nUpdates); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (updatesRequest == MissedUpdatesRequest.EMPTY) { log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); } return updatesRequest; } } |
blob | Not specified | f | f | f | false | 0 | 2236 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/PeerSync.java/#L787-L856 | 2 | 196 | 2236 | minor | |
| 828 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Method chaining 5. Magic numbers 6. Inconsistent variable naming 7. Complex method body 8. Nested if statements 9. Too many parameters in method signatures 10. Unused variables 11. Long variable names 12. Use of primitive types instead of objects 13. Too many comments 14. Lack of proper indentation and formatting 15. Unnecessary casting and conversions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
blob | Long method2 Feature envy3 Duplicate code4 Method chaining5 Magic numbers6 Inconsistent variable naming7 Complex method body8 Nested if statements9 Too many parameters in method signatures | t | f | f | . Long method2. Feature envy3. Duplicate code4. Method chaining5. Magic numbers6. Inconsistent variable naming7. Complex method body8. Nested if statements9. Too many parameters in method signatures | blob | 0 | 7726 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 2 | 828 | 7726 | major |
| 153 | { "response": "YES I found bad smells. The bad smells are: 1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | Not specified | f | f | f | false | 0 | 1932 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 2 | 153 | 1932 | minor | |
| 546 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements MethodInterceptor { // ~ Instance fields // ================================================================================================ private MethodSecurityMetadataSource securityMetadataSource; // ~ Methods // ======================================================================================================== public Class getSecureObjectClass() { return MethodInvocation.class; } /** * This method should be used to enforce security on a MethodInvocation. * * @param mi The method being invoked which requires a security decision * * @return The returned value from the method invocation (possibly modified by the * {@code AfterInvocationManager}). * * @throws Throwable if any error occurs */ public Object invoke(MethodInvocation mi) throws Throwable { InterceptorStatusToken token = super.beforeInvocation(mi); Object result; try { result = mi.proceed(); } finally { super.finallyInvocation(token); } return super.afterInvocation(token, result); } public MethodSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 5550 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptor.java/#L40-L88 | 2 | 546 | 5550 | major |
| 3849 | {"message": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int year = gc.cdate.getNormalizedYear(); if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); BaseCalendar.Date d = getCalendarDate(month1); return d.getDayOfMonth(); } } return getMinimum(field); } /** * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current |
feature envy | f | f | f | feature envy | 0 | 9990 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java/#L1674-L1686 | 1 | 3849 | 9990 | minor | ||
| 1465 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 11030 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 | 2 | 1465 | 11030 | major |
| 727 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic number 4. Inefficient algorithm 5. Unnecessary variable assignments 6. Repeated code/logic 7. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class BucketList implements Iterable> { private final ArrayList> bucketList; private final List> immutableVisibleList; private BucketList(ArrayList> bucketList, ArrayList> publicBucketList) { this.bucketList = bucketList; int displayIndex = 0; for (Bucket bucket : publicBucketList) { bucket.displayIndex = displayIndex++; } immutableVisibleList = Collections.unmodifiableList(publicBucketList); } private int getBucketCount() { return immutableVisibleList.size(); } private int getBucketIndex(CharSequence name, Collator collatorPrimaryOnly) { // binary search int start = 0; int limit = bucketList.size(); while ((start + 1) < limit) { int i = (start + limit) / 2; Bucket bucket = bucketList.get(i); int nameVsBucket = collatorPrimaryOnly.compare(name, bucket.lowerBoundary); if (nameVsBucket < 0) { limit = i; } else { start = i; } } Bucket bucket = bucketList.get(start); if (bucket.displayBucket != null) { bucket = bucket.displayBucket; } return bucket.displayIndex; } /** * Private iterator over all the buckets, visible and invisible */ private Iterator> fullIterator() { return bucketList.iterator(); } /** * Iterator over just the visible buckets. */ @Override public Iterator> iterator() { return immutableVisibleList.iterator(); // use immutable list to prevent remove(). } } |
blob | Long method2 Feature envy3 Magic number4 Inefficient algorithm 5 Unnecessary variable assignments6 Repeated code/logic7 Lack of comments/documentation | t | f | f | . Long method2. Feature envy3. Magic number4. Inefficient algorithm 5. Unnecessary variable assignments6. Repeated code/logic7. Lack of comments/documentation | blob | 0 | 6852 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/AlphabeticIndex.java/#L1101-L1154 | 2 | 727 | 6852 | minor |
| 473 | YES I found bad smells The bad smells are: 1. Inconsistent formatting and style - inconsistent use of spaces and indentation. 2. Unused fields and redundant constructors - the field "taskId" and the constructor are not used. 3. Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem". 4. Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | Inconsistent formatting and style - inconsistent use of spaces and indentation2 Unused fields and redundant constructors - the field "taskId" and the constructor are not used3 Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem"4 Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface | t | f | f | . Inconsistent formatting and style - inconsistent use of spaces and indentation.2. Unused fields and redundant constructors - the field "taskId" and the constructor are not used.3. Poor naming convention - "TaskRemoval" is a confusing name for a class that implements "WorkerHistoryItem".4. Feature envy - the "getTaskId()" method only uses the "taskId" field, which could easily be a method of the "WorkerHistoryItem" interface. | data class | 0 | 4576 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 2 | 473 | 4576 | minor |
| 1864 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
data class | blob | t | t | f | blob | data class | 0 | 12232 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 1 | 1864 | 12232 | critical |
| 1016 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | 1: long method | t | t | f | 1: long method | data class | 0 | 9303 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 1 | 1016 | 9303 | minor |
| 2478 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 14590 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 1 | 2478 | 14590 | major |
| 392 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 3965 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 392 | 3965 | major |
| 793 | {"answer":"YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 7553 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 793 | 7553 | minor |
| 901 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8158 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 2 | 901 | 8158 | minor |
| 1770 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
blob | Data Class, Long Method | t | f | f | Data Class, Long Method | blob | 0 | 11919 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 1770 | 11919 | major |
| 1074 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 9629 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 1074 | 9629 | major |
| 2566 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14868 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 1 | 2566 | 14868 | minor |
| 1020 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 9347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 1020 | 9347 | minor |
| 1639 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 11533 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L26965-L27327 | 2 | 1639 | 11533 | minor | ||
| 2083 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } } |
blob | data class | t | t | f | data class | blob | 0 | 13077 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 | 1 | 2083 | 13077 | minor |
| 4451 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 11797 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 2 | 4451 | 11797 | minor |
| 352 | {"message": "NO, I did not find any bad smell"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DBMsgConstants { public static final int MAX_BODY_SIZE = 64 * 1024 * 1024; //64KB } |
data class | f | f | f | data class | 0 | 3605 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/constant/DBMsgConstants.java/#L20-L22 | 1 | 352 | 3605 | critical | ||
| 1806 | YES I found bad smellsthe bad smells are:- 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Long method | t | f | f | . Long method | data class | 0 | 12041 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 2 | 1806 | 12041 | minor |
| 2151 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
blob | data class | t | t | f | data class | blob | 0 | 13293 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 2151 | 13293 | minor |
| 5268 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Scanner { private final List tokens; private int currentPosition = 0; public Scanner(final List tokens) { this.tokens = tokens; } public NodeSelect scan() { return scanSelect(); } public void checkTail() { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && (item1.getNodeType() != NodeType.OPERATION || item1.getValue().length() != 0)) { currentPosition = num1; throwSyntaxError(SyntaxError.EXPECTING_END_OF_STRING); } } private NodeSelect scanSelect() { final Node node1 = ensureToken(NodeType.NAME, "select", SyntaxError.EXPECTING_SELECT); //$NON-NLS-1$ final NodeSelect select1 = new NodeSelect(); if (scanToken(NodeType.OPERATION, "*") != null) //$NON-NLS-1$ { select1.setFields(null); } else { select1.setFields(scanFieldNameList(false, NodeType.FIELD_LIST)); } while (true) { if (scanToken(NodeType.NAME, "from") != null) //$NON-NLS-1$ { if (select1.getFrom() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_FROM); } select1.setFrom(scanTableName()); continue; } if (scanToken(NodeType.NAME, "where") != null) //$NON-NLS-1$ { if (select1.getWhere() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_WHERE); } select1.setWhere(scanWhere(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getGroupBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_GROUP_BY); } select1.setGroupBy(scanFieldNameList(false, NodeType.GROUP_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "order") != null) //$NON-NLS-1$ { ensureToken(NodeType.NAME, "by", SyntaxError.EXPECTING_BY); //$NON-NLS-1$ if (select1.getOrderBy() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_ORDER_BY); } select1.setOrderBy(scanFieldNameList(true, NodeType.ORDER_FIELD_LIST)); continue; } if (scanToken(NodeType.NAME, "asof") != null) //$NON-NLS-1$ { if (select1.getAsOf() != null) { --currentPosition; throwSyntaxError(SyntaxError.DUPLICATE_AS_OF); } select1.setAsOf(scanValue(select1.getFrom())); continue; } if (scanToken(NodeType.NAME, "mode") != null) //$NON-NLS-1$ { if (select1.getMode() != null) { currentPosition--; throwSyntaxError(SyntaxError.DUPLICATE_MODE); } select1.setMode(ScanMode()); continue; } select1.setStartOffset(node1.getStartOffset()); select1.setEndOffset(((NodeItem) tokens.get(tokens.size() - 1)).getEndOffset()); return select1; } } private Node scanWhere(final NodeTableName table) { return scanCondition4(table); } private Node scanCondition4(final NodeTableName table) { Node node1 = scanCondition3(table); NodeOrOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "or"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "||"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeOrOperator(); operator1.add(node1); } operator1.add(scanCondition3(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition3(final NodeTableName table) { Node node1 = scanCondition2(table); NodeAndOperator operator1 = null; while (true) { Node node2 = scanToken(NodeType.NAME, "and"); //$NON-NLS-1$ if (node2 == null) { node2 = scanToken(NodeType.OPERATION, "&&"); //$NON-NLS-1$ } if (node2 == null) { break; } if (operator1 == null) { operator1 = new NodeAndOperator(); operator1.add(node1); } operator1.add(scanCondition2(table)); } if (operator1 != null) { operator1.setStartOffset(operator1.getItem(0).getStartOffset()); operator1.setEndOffset(operator1.getItem(operator1.getCount() - 1).getEndOffset()); node1 = operator1; } return node1; } private Node scanCondition2(final NodeTableName table) { Node node1 = scanToken(NodeType.NAME, "not"); //$NON-NLS-1$ if (node1 == null) { node1 = scanToken(NodeType.OPERATION, "!"); //$NON-NLS-1$ } if (node1 != null) { final Node node2 = scanCondition2(table); final Node node3 = new NodeNotOperator(node2); node3.setStartOffset(node1.getStartOffset()); node3.setEndOffset(node2.getEndOffset()); return node3; } node1 = scanToken(NodeType.NAME, "ever"); //$NON-NLS-1$ if (node1 != null) { final Node node4 = scanCondition2(table); final Node node5 = new NodeEverOperator(node4); node5.setStartOffset(node1.getStartOffset()); node5.setEndOffset(node4.getEndOffset()); return node5; } node1 = scanToken(NodeType.NAME, "never"); //$NON-NLS-1$ if (node1 != null) { final Node node6 = scanCondition2(table); final Node node7 = new NodeNotOperator(new NodeEverOperator(node6)); node7.setStartOffset(node1.getStartOffset()); node7.setEndOffset(node6.getEndOffset()); return node7; } return scanCondition1(table); } private Node scanCondition1(final NodeTableName table) { final Node node1 = scanToken(NodeType.OPERATION, "("); //$NON-NLS-1$ if (node1 != null) { final Node node2 = scanWhere(table); final Node node3 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ node2.setStartOffset(node1.getStartOffset()); node2.setEndOffset(node3.getEndOffset()); node2.setHasParantheses(true); return node2; } final NodeCondition condition1 = new NodeCondition(); Node node4 = condition1; condition1.setLeft(scanFieldName(table)); final Stack stack1 = new Stack(); while (true) { if (scanToken(NodeType.NAME, "not") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); continue; } if (scanToken(NodeType.NAME, "ever") != null) //$NON-NLS-1$ { stack1.push(NodeType.EVER); continue; } if (scanToken(NodeType.NAME, "never") != null) //$NON-NLS-1$ { stack1.push(NodeType.NOT); stack1.push(NodeType.EVER); continue; } break; } while (true) { if (stack1.size() <= 0) { condition1.setCondition(scanConditionOperator(node4 != condition1)); if (condition1.getCondition() == Condition.NONE) { throwSyntaxError(SyntaxError.EXPECTING_COMPARISON_OPERATOR); } if (condition1.getCondition() == Condition.GROUP) { condition1.setRight(scanValue(table)); } else if (condition1.getCondition() == Condition.IN) { final Node node5 = ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final Node node6 = scanValueList(table); final Node node7 = ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ node6.setStartOffset(node5.getStartOffset()); node6.setEndOffset(node7.getEndOffset()); condition1.setRight(node6); } else if (condition1.getCondition() == Condition.UNDER) { condition1.setRight(scanValue(table)); } else { Node node8 = TryScanFieldName(); if (node8 == null) { node8 = TryScanExpression(); } if (node8 != null) { condition1.setRight(node8); } else { throwSyntaxError(SyntaxError.EXPECTING_FIELD_OR_EXPRESSION); } } node4.setStartOffset(condition1.getLeft().getStartOffset()); node4.setEndOffset(condition1.getRight().getEndOffset()); return node4; } final NodeType nodeType = stack1.pop(); if (nodeType == NodeType.NOT) { node4 = new NodeNotOperator(node4); } else if (nodeType == NodeType.EVER) { node4 = new NodeEverOperator(node4); } } } private Node scanValueList(final NodeTableName table) { final NodeValueList list1 = new NodeValueList(); do { list1.add(scanExpression(table)); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ list1.setStartOffset(list1.getItem(0).getStartOffset()); list1.setEndOffset(list1.getItem(list1.getCount() - 1).getEndOffset()); return list1; } private Node scanValue(final NodeTableName table) { final Node node = TryScanSingleValue(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); } return node; } private Node scanExpression(final NodeTableName nodeTable) { final Node node = TryScanExpression(); if (node == null) { throwSyntaxError(SyntaxError.EXPECTING_VALUE); return null; } return node; } private Condition scanConditionOperator(final boolean afterNotOrEver) { final int num1 = currentPosition; final NodeItem item1 = nextToken(); if ((item1 != null) && ((item1.getNodeType() == NodeType.NAME) || ((item1.getNodeType() == NodeType.OPERATION) && !afterNotOrEver))) { Condition condition1 = ConditionalOperators.find(item1.getValue()); if (condition1 == Condition.IN && scanToken(NodeType.NAME, "group") != null) //$NON-NLS-1$ { condition1 = Condition.GROUP; } else if (condition1 == Condition.CONTAINS && scanToken(NodeType.NAME, "words") != null) //$NON-NLS-1$ { condition1 = Condition.CONTAINS_WORDS; } if (condition1 != Condition.NONE) { return condition1; } } currentPosition = num1; if (!afterNotOrEver) { return Condition.NONE; } return Condition.EQUALS; } private NodeTableName scanTableName() { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == NodeType.NAME) { return new NodeTableName((NodeName) tokenNode); } currentPosition = savedCurrentPosition; throwSyntaxError(SyntaxError.EXPECTING_TABLE_NAME); return null; } // direction is true if each field name in the field name list can be // suffixed by an optional // direction indicator - asc or desc private NodeFieldList scanFieldNameList(final boolean direction, final NodeType nodeType) { final NodeFieldList fieldListNode = new NodeFieldList(nodeType); while (true) { final NodeFieldName fieldNameNode = scanFieldName(null); if (direction) { if (scanToken(NodeType.NAME, "asc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.ASCENDING); } else if (scanToken(NodeType.NAME, "desc") != null) //$NON-NLS-1$ { fieldNameNode.setDirection(Direction.DESCENDING); } } fieldListNode.add(fieldNameNode); /* * if the next token is not a comma operator, then the field list is * finished */ if (scanToken(NodeType.OPERATION, ",") == null) //$NON-NLS-1$ { if (fieldListNode.getCount() != 0) { /* * if the field list node is not empty, set it's start and * end offset by using the starting and ending node in the * list */ fieldListNode.setStartOffset(fieldListNode.getItem(0).getStartOffset()); fieldListNode.setEndOffset(fieldListNode.getItem(fieldListNode.getCount() - 1).getEndOffset()); } return fieldListNode; } } } private NodeFieldName scanFieldName(final NodeTableName table) { final Node node = TryScanFieldName(); if (node != null) { return (NodeFieldName) node; } throwSyntaxError(SyntaxError.EXPECTING_FIELD_NAME); return null; } private NodeMode ScanMode() { ensureToken(NodeType.OPERATION, "(", SyntaxError.EXPECTING_LEFT_BRACKET); //$NON-NLS-1$ final NodeMode mode = new NodeMode(); do { final int pos = currentPosition; final NodeItem item = nextToken(); if ((item == null) || !(item.getNodeType().equals(NodeType.NAME))) { currentPosition = pos; throwSyntaxError(SyntaxError.EXPECTING_MODE); return null; } mode.add(item); } while (scanToken(NodeType.OPERATION, ",") != null); //$NON-NLS-1$ ensureToken(NodeType.OPERATION, ")", SyntaxError.EXPECTING_RIGHT_BRACKET); //$NON-NLS-1$ mode.setStartOffset(mode.getItem(0).getStartOffset()); mode.setEndOffset(mode.getItem(mode.getCount() - 1).getEndOffset()); return mode; } private NodeItem ensureToken(final NodeType type, final String str, final SyntaxError syntaxError) { final NodeItem tokenNode = scanToken(type, str); if (tokenNode == null) { throwSyntaxError(syntaxError); } return tokenNode; } private void throwSyntaxError(final SyntaxError error) { NodeItem causeNode = null; if (currentPosition < tokens.size()) { causeNode = (NodeItem) tokens.get(currentPosition); } throw new SyntaxException(causeNode, error); } private NodeItem scanToken(final NodeType type, final String str) { final int savedCurrentPosition = currentPosition; final NodeItem tokenNode = nextToken(); if (tokenNode != null && tokenNode.getNodeType() == type && str.equalsIgnoreCase(tokenNode.getValue())) { return tokenNode; } currentPosition = savedCurrentPosition; return null; } private NodeItem nextToken() { if (currentPosition < tokens.size()) { return (NodeItem) tokens.get(currentPosition++); } return null; } private Node TryScanExpression() { int num; Node node = TryScanSingleValue(); if (node == null) { return null; } while (true) { num = currentPosition; final NodeItem item = nextToken(); if (item != null) { Arithmetic none = Arithmetic.NONE; Node node2 = null; if (item.getNodeType() == NodeType.NUMBER) { none = ArithmeticalOperators.find(item.getValue().substring(0, 1)); if (none != Arithmetic.NONE) { item.setValue(item.getValue().substring(1)); node2 = item; } } else if (item.getNodeType() == NodeType.OPERATION) { none = ArithmeticalOperators.find(item.getValue()); if (none != Arithmetic.NONE) { node2 = TryScanSingleValue(); } } if ((none != Arithmetic.NONE) && (node2 != null)) { final NodeArithmetic arithmetic2 = new NodeArithmetic(); arithmetic2.setArithmetic(none); arithmetic2.setLeft(node); arithmetic2.setRight(node2); arithmetic2.setStartOffset(arithmetic2.getLeft().getStartOffset()); arithmetic2.setEndOffset(arithmetic2.getRight().getEndOffset()); node = arithmetic2; continue; } } currentPosition = num; return node; } } private Node TryScanFieldName() { Node node = null; final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (node2.getNodeType() == NodeType.NAME)) { final NodeItem item = scanToken(NodeType.OPERATION, "."); //$NON-NLS-1$ Node node3 = null; if (item != null) { node3 = nextToken(); if ((node3 != null) && (node3.getNodeType() == NodeType.NAME)) { node = new NodeFieldName((NodeName) node2, (NodeName) node3); } } else { node = new NodeFieldName((NodeName) node2); } } if (node == null) { currentPosition = pos; return null; } return node; } private Node TryScanSingleValue() { final int pos = currentPosition; final Node node2 = nextToken(); if ((node2 != null) && (((node2.getNodeType() == NodeType.NUMBER) || (node2.getNodeType() == NodeType.STRING)) || ((node2.getNodeType() == NodeType.VARIABLE) || (node2.getNodeType() == NodeType.BOOL_VALUE)))) { return node2; } currentPosition = pos; return null; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14729 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/workitem/internal/wiqlparse/Scanner.java/#L9-L514 | 2 | 5268 | 14729 | minor |
| 2030 | YES I found bad smells the bad smells are: 1. Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class. This could potentially lead to issues with data consistency and violates the principle of encapsulation. 2. Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain. 3. Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen. 4. Inconsistent formatting - Some methods have Javadoc comments, while others do not. This inconsistency can make the code harder to read and understand. 5. Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code. 6. Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files. A more accurate name for these methods would be getCertificate() and getPrivateKey(). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class This could potentially lead to issues with data consistency and violates the principle of encapsulation2 Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain3 Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen4 Inconsistent formatting - Some methods have Javadoc comments, while others do not This inconsistency can make the code harder to read and understand5 Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code6 Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files A more accurate name for these methods would be getCertificate() and getPrivateKey() | t | f | f | . Feature envy - The getSharedSecret() and setSharedSecret() methods are only accessing and modifying the sharedSecret variable, which is not a part of this class. This could potentially lead to issues with data consistency and violates the principle of encapsulation.2. Long method - The class contains multiple methods with a significant amount of code, making it difficult to read and maintain.3. Magic numbers - The tokenExpirationSeconds and the minimum length for the shared secret are set with arbitrary values, making it unclear why those specific values were chosen.4. Inconsistent formatting - Some methods have Javadoc comments, while others do not. This inconsistency can make the code harder to read and understand.5. Unused code - The isAppropriateForCreating() and isAppropriateForValidating() methods are not utilized in the class and can be considered dead code.6. Misleading method names - The getCertPath() and getKeyPath() methods imply that they are retrieving paths, but they are actually returning the actual data contained in those files. A more accurate name for these methods would be getCertificate() and getPrivateKey(). | data class | 0 | 12809 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 2 | 2030 | 12809 | minor |
| 2147 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 13277 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 2 | 2147 | 13277 | major |
| 1398 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long Method | t | f | f | Long Method | feature envy | 0 | 10855 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1398 | 10855 | minor |
| 414 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 4220 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 1 | 414 | 4220 | major |
| 2704 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | long method | t | t | f | long method | data class | 0 | 15338 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 2704 | 15338 | major |
| 1795 | YES I found bad smells. The bad smells are: 1. Long method, 2. Duplicate code, 3. Magic numbers, 4. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | Long method, 2 Duplicate code, 3 Magic numbers, 4 Shotgun surgery | t | f | f | . Long method, 2. Duplicate code, 3. Magic numbers, 4. Shotgun surgery | feature envy | 0 | 11998 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1795 | 11998 | minor |
| 1171 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 10196 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 2 | 1171 | 10196 | minor |
| 703 | YES I found bad smells the bad smells are: 1. Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it. This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself. 2. Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code. This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability. 3. Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code. It would be better to group the related parameters into separate objects and pass them instead. 4. Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic. This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class. 5. Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks. This should be simplified for better readability and maintainability. 6. Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri. This indicates that this logic can be extracted into a separate method to avoid repetition. 7. Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc. These should be replaced with proper objects for better readability and maintainability. 8. Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors. 9. Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues. 10. Non-meaningful comments: The comments in the setter methods of RemoteProcessGroupDTO class are not helpful and do not provide any additional information. This could be considered as unnecessary clutter in the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
blob | Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself2 Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability3 Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code It would be better to group the related parameters into separate objects and pass them instead4 Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class5 Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks This should be simplified for better readability and maintainability6 Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri This indicates that this logic can be extracted into a separate method to avoid repetition7 Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc These should be replaced with proper objects for better readability and maintainability8 Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors9 Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues | t | f | f | . Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it. This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself.2. Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code. This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability.3. Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code. It would be better to group the related parameters into separate objects and pass them instead.4. Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic. This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class.5. Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks. This should be simplified for better readability and maintainability.6. Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri. This indicates that this logic can be extracted into a separate method to avoid repetition.7. Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc. These should be replaced with proper objects for better readability and maintainability.8. Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors.9. Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues. | blob | 0 | 6698 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 703 | 6698 | major |
| 2010 | YES, I found bad smells.the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LayoutContext { /** * An {@link LayoutContext} notifies registered listeners about changes to * the layout algorithm using this property name. */ public static final String LAYOUT_ALGORITHM_PROPERTY = "layoutAlgorithm"; private ObjectProperty layoutAlgorithmProperty = new SimpleObjectProperty<>( this, LAYOUT_ALGORITHM_PROPERTY); private Graph graph; private final List postLayoutPass = new ArrayList<>(); private final List preLayoutPass = new ArrayList<>(); private final List layoutFilters = new ArrayList<>(); /** * Adds the given ILayoutFilter to this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to add to this context. */ public void addLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.add(layoutFilter); } /** * Applies the layout algorithm of this LayoutContext. The clean flag is * passed-in to the layout algorithm to indicate whether the context changed * significantly since the last layout pass. * * @param clear * true to indicate that the algorithm has to fully * re-compute the layout, otherwise false. */ public void applyLayout(boolean clear) { ILayoutAlgorithm layoutAlgorithm = layoutAlgorithmProperty.get(); if (layoutAlgorithm != null) { preLayout(); layoutAlgorithm.applyLayout(this, clear); postLayout(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run after the layout pass. Should not be * called by clients. */ public void postLayout() { for (Runnable r : new ArrayList<>(postLayoutPass)) { r.run(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run before the layout pass. Should not be * called by clients. */ public void preLayout() { for (Runnable r : preLayoutPass) { r.run(); } } /** * Returns the graph that is to be layouted. * * @return The {@link Graph} that is to be layouted. */ public Graph getGraph() { return graph; } /** * Sets the graph that is to be layouted by this context. * * @param graph * The {@link Graph} to layout. */ public void setGraph(Graph graph) { // TODO: we should not allow to pass in null here. Instead we should // guard ourselves against null. if (graph == null) { graph = new Graph(); } this.graph = graph; } /** * Returns all the nodes that should be laid out. Replacing elements in the * returned array does not affect this context. * * @return array of nodes to lay out */ // TODO: remove this (algorithms should use getGraph().getNodes()) public Node[] getNodes() { ObservableList nodes = graph.getNodes(); List layoutRelevantNodes = new ArrayList<>(); for (Node n : nodes) { if (!isLayoutIrrelevant(n)) { layoutRelevantNodes.add(n); } } return layoutRelevantNodes.toArray(new Node[] {}); } /** * Returns all the connections between nodes that should be laid out. * Replacing elements in the returned array does not affect this context. * * @return array of connections between nodes */ public Edge[] getEdges() { ObservableList edges = graph.getEdges(); List layoutRelevantEdges = new ArrayList<>(); for (Edge e : edges) { if (!isLayoutIrrelevant(e)) { layoutRelevantEdges.add(e); } } return layoutRelevantEdges.toArray(new Edge[] {}); } /** * Returns the static layout algorithm used to layout a newly initialized * graph or after heavy changes to it. * * @return The layout algorithm that is used by this {@link LayoutContext}. */ public ILayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithmProperty.get(); } /** * Returns true when the given {@link Edge} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param edge * The {@link Edge} in question. * @return true when the given {@link Edge} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Edge edge) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(edge)) { return true; } } return false; } /** * Returns true when the given {@link Node} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param nodeLayout * The {@link Node} in question. * @return true when the given {@link Node} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Node nodeLayout) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(nodeLayout)) { return true; } } return false; } /** * A property representing the layout algorithm used by this * {@link LayoutContext}. * * @see #getLayoutAlgorithm() * @see #setLayoutAlgorithm(ILayoutAlgorithm) * * @return A property named {@link #LAYOUT_ALGORITHM_PROPERTY}. */ public ObjectProperty layoutAlgorithmProperty() { return layoutAlgorithmProperty; }; /** * Removes the given ILayoutFilter from this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to remove to this context. */ public void removeLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.remove(layoutFilter); } /** * Adds the given {@link Runnable} to the list of runnables which are called * when this {@link LayoutContext} is asked to apply all changes made to its * elements to the display. * * @param runnable * A {@link Runnable} called whenever this context is asked to * apply all changes made to its elements to the display. */ public void schedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!postLayoutPass.contains(runnable)) { postLayoutPass.add(runnable); } } /** * Adds the given {@link Runnable} to the list of {@link Runnable}s which * are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to add to the list of {@link Runnable}s * which are executed before applying a layout. */ public void schedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!preLayoutPass.contains(runnable)) { preLayoutPass.add(runnable); } } /** * Sets the layout algorithm for this context. * * @param algorithm * The new {@link ILayoutAlgorithm} for this * {@link LayoutContext}. */ public void setLayoutAlgorithm(ILayoutAlgorithm algorithm) { layoutAlgorithmProperty.set(algorithm); } /** * Removes the given {@link Runnable} from the list of runnables which are * called when this {@link LayoutContext} is asked to apply all changes made * to its elements to the display. * * @param runnable * The {@link Runnable} that should no longer get called when * flushing changes. */ public void unschedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (postLayoutPass.contains(runnable)) { postLayoutPass.remove(runnable); } } /** * Removes the given {@link Runnable} from the list of {@link Runnable}s * which are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to remove from the list of * {@link Runnable}s which are executed before applying a layout. */ public void unschedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (preLayoutPass.contains(runnable)) { preLayoutPass.remove(runnable); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 12748 | https://github.com/eclipse/gef/blob/8f2649b90ab14a1bb010188036d4eedf7586e123/org.eclipse.gef.layout/src/org/eclipse/gef/layout/LayoutContext.java/#L35-L315 | 2 | 2010 | 12748 | major |
| 5774 | {"message": "YES I found bad smells"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Not specified | f | f | f | "YES I found bad smells"} | false | 0 | 14902 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 2 | 5774 | 14902 | major |
| 1589 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Feature envy | t | f | f | . Feature envy | data class | 0 | 11385 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 1589 | 11385 | minor |
| 5480 | NO, I did not find any bad smells. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | f | f | f | long method | 0 | 1191 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5480 | 1191 | minor | ||
| 1720 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | t | f | f | data class | 0 | 11795 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 1720 | 11795 | minor | ||
| 2017 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | f | f | f | blob | 0 | 12773 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 | 1 | 2017 | 12773 | major | ||
| 75 | {"error": "Unsupported text format for the request. Please provide the input in plain text format."} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class State { public Map properties = new HashMap(); public Map array_properties = new HashMap(); } |
data class | Not specified | f | f | f | false | 0 | 1125 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/intellij/ApplicationSettings.java/#L58-L61 | 1 | 75 | 1125 | major | |
| 2212 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 13524 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 2 | 2212 | 13524 | minor |
| 184 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextListenerStartup implements ServletContextListener { /** Configuration file path parameter name. */ public static final String IGNITE_CFG_FILE_PATH_PARAM = "IgniteConfigurationFilePath"; /** Names of started Ignite instances. */ private final Collection igniteInstanceNames = new ArrayList<>(); /** {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent evt) { ServletContext ctx = evt.getServletContext(); String cfgFile = ctx.getInitParameter(IGNITE_CFG_FILE_PATH_PARAM); Collection cfgs; GridSpringResourceContext rsrcCtx = null; if (cfgFile != null) { URL cfgUrl = null; try { cfgUrl = evt.getServletContext().getResource("/META-INF/" + cfgFile); } catch (MalformedURLException ignored) { // Ignore, we still need to try with IGNITE_HOME. } if (cfgUrl == null) // Try with IGNITE_HOME and with context class loader. cfgUrl = U.resolveIgniteUrl(cfgFile); if (cfgUrl == null) throw new IgniteException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile); IgniteBiTuple, ? extends GridSpringResourceContext> t; try { t = IgnitionEx.loadConfigurations(cfgUrl); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to load Ignite configuration.", e); } cfgs = t.get1(); rsrcCtx = t.get2(); if (cfgs.isEmpty()) throw new IgniteException("Can't find grid factory configuration in: " + cfgUrl); } else cfgs = Collections.singleton(new IgniteConfiguration()); try { assert !cfgs.isEmpty(); for (IgniteConfiguration cfg : cfgs) { assert cfg != null; Ignite ignite; synchronized (ServletContextListenerStartup.class) { try { ignite = G.ignite(cfg.getIgniteInstanceName()); } catch (IgniteIllegalStateException ignored) { ignite = IgnitionEx.start(new IgniteConfiguration(cfg), rsrcCtx); } } // Check if grid is not null - started properly. if (ignite != null) igniteInstanceNames.add(ignite.name()); } } catch (IgniteCheckedException e) { // Stop started grids only. for (String name : igniteInstanceNames) G.stop(name, true); throw new IgniteException("Failed to start Ignite.", e); } } /** {@inheritDoc} */ @Override public void contextDestroyed(ServletContextEvent evt) { // Stop started grids only. for (String name: igniteInstanceNames) G.stop(name, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ServletContextListenerStartup.class, this); } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 2104 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/web/src/main/java/org/apache/ignite/startup/servlet/ServletContextListenerStartup.java/#L95-L189 | 1 | 184 | 2104 | major |
| 5004 | { "response": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 13760 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5004 | 13760 | major | ||
| 5640 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 10919 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5640 | 10919 | major |
| 392 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 3965 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 392 | 3965 | major |
| 2441 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy, 3. Repeated code, 4. Data clumps, 5. Inconsistent naming conventions, 6. Inconsistent code formatting, 7. Excessive comments, 8. Misplaced code, 9. Lack of encapsulation, 10. Non-descriptive variable names. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
blob | Long method, 2 Feature envy, 3 Repeated code, 4 Data clumps, 5 Inconsistent naming conventions, 6 Inconsistent code formatting, 7 Excessive comments, 8 Misplaced code, 9 Lack of encapsulation, | t | f | f | . Long method, 2. Feature envy, 3. Repeated code, 4. Data clumps, 5. Inconsistent naming conventions, 6. Inconsistent code formatting, 7. Excessive comments, 8. Misplaced code, 9. Lack of encapsulation, | blob | 0 | 14481 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 2441 | 14481 | minor |
| 1057 | YES I found bad smells the bad smells are: 1. Long class 2. Long method 3. Feature envy (Options are added outside of the class, so the class is dependent on external options) 4. Magic number (option names and descriptions are repeated frequently and can easily introduce errors) 5. Static field (logger field is used for all instances) 6. Single responsibility principle violation (class contains both option handling and execution logic) 7. Inconsistent naming (OPTION_CUBE_NAME vs cubeName, OPTION_INPUT_PATH vs inputPath, etc.) 8. Code duplication (multiple uses of similar code for adding and setting options) 9. Use of synchronized methods, which can cause performance issues in multithreaded environments 10. Excessive use of transient keyword, which can be a symptom of avoiding proper serialization and deserialization of objects 11. Use of deprecated methods (e.g. OptionBuilder.withArgName()) 12. Unnecessary type casting (Class.forName("scala.reflect.ClassTag$$anon$1")) 13. Lack of comments and documentation, making the code difficult to understand and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | Long class2 Long method3 Feature envy (Options are added outside of the class, so the class is dependent on external options)4 Magic number (option names and descriptions are repeated frequently and can easily introduce errors)5 Static field (logger field is used for all instances)6 Single responsibility principle violation (class contains both option handling and execution logic)7 Inconsistent naming (OPTION_CUBE_NAME vs cubeName, OPTION_INPUT_PATH vs inputPath, etc)8 Code duplication (multiple uses of similar code for adding and setting options)9 Use of synchronized methods, which can cause performance issues in multithreaded environments | t | f | f | . Long class2. Long method3. Feature envy (Options are added outside of the class, so the class is dependent on external options)4. Magic number (option names and descriptions are repeated frequently and can easily introduce errors)5. Static field (logger field is used for all instances)6. Single responsibility principle violation (class contains both option handling and execution logic)7. Inconsistent naming (OPTION_CUBE_NAME vs cubeName, OPTION_INPUT_PATH vs inputPath, etc.)8. Code duplication (multiple uses of similar code for adding and setting options)9. Use of synchronized methods, which can cause performance issues in multithreaded environments | blob | 0 | 9518 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 2 | 1057 | 9518 | minor |
| 4484 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent naming 5. Excessive comments 6. Inconsistent formatting 7. Complex conditional logic 8. Complex nested loops 9. Data class 10. Message chains 11. Excessive parameters 12. Inadequate naming 13. Inconsistent error handling 14. Improper exception handling 15. Poor separation of concerns 16. Excessive use of public fields/variables 17. Excessive use of null checks 18. Inconsistent use of types 19. Inconsistent use of language features 20. Magic numbers/strings 21. Unused variables/parameters 22. Dead code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } } |
blob | Long method2 Feature envy3 Duplicated code4 Inconsistent naming5 Excessive comments6 Inconsistent formatting7 Complex conditional logic8 Complex nested loops9 Data class | t | f | f | . Long method2. Feature envy3. Duplicated code4. Inconsistent naming5. Excessive comments6. Inconsistent formatting7. Complex conditional logic8. Complex nested loops9. Data class | blob | 0 | 11873 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 | 2 | 4484 | 11873 | major |
| 2007 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } } |
blob | long method | t | t | f | long method | blob | 0 | 12736 | https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 | 1 | 2007 | 12736 | critical |
| 143 | {"response":"YES I found bad smells", "the bad smells are":[ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 1786 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 2 | 143 | 1786 | major |
| 2199 | of the code above. NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
data class | f | f | f | data class | 0 | 13495 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 2 | 2199 | 13495 | major | ||
| 1602 | YES, I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static final class SymbolComparator implements Comparator { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object arg0, Object arg1) { long addr0=0; long addr1=0; // arg0 and arg1 will be Symbol objects if (arg0 instanceof Symbol) { Symbol S0 = (Symbol) arg0; Symbol S1 = (Symbol) arg1; addr0 = S0.symbolStart; addr1 = S1.symbolStart; } else { addr0 = ((Long)arg0).longValue(); addr1 = ((Long)arg1).longValue(); } // both +ve if (addr0 >= 0 && addr1 >=0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return -1; return 1; } // both -ve if (addr0 < 0 && addr1 < 0) { if (addr0 == addr1) return 0; if (addr0 < addr1) return 1; return -1; } if (addr0 < 0 && addr1 >=0) { return 1; } return -1; } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | blob | 0 | 11430 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/Symbol.java/#L134-L175 | 2 | 1602 | 11430 | minor |
| 1894 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12321 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 1894 | 12321 | minor |
| 2126 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | f | f | f | data class | 0 | 13221 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 2 | 2126 | 13221 | critical | ||
| 4577 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 12170 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 | 2 | 4577 | 12170 | major |
| 1568 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 11331 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 2 | 1568 | 11331 | minor |
| 2142 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | long method | t | t | f | long method | data class | 0 | 13268 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 2142 | 13268 | major |
| 1848 | {"response":"YES I found bad smells","the bad smells are":["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 12186 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 2 | 1848 | 12186 | minor |
| 5233 | { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 14632 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 1 | 5233 | 14632 | major |
| 3200 | NO, I did not find any bad smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 4807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities.ide/src-gen/org/eclipse/xtext/idea/example/entities/ide/contentassist/antlr/internal/InternalEntitiesParser.java/#L3864-L3892 | 2 | 3200 | 4807 | minor | ||
| 132 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 1631 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 2 | 132 | 1631 | critical |
| 907 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 8199 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 1 | 907 | 8199 | minor |
| 2459 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 14536 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 | 2 | 2459 | 14536 | minor |
| 850 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 7851 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 2 | 850 | 7851 | critical |
| 58 | {"response": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @AutoValue abstract class UOfKind extends UExpression { public static UOfKind create(UExpression expression, Set allowed) { return new AutoValue_UOfKind(expression, allowed); } abstract UExpression expression(); abstract Set allowed(); @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { return expression().inline(inliner); } @Override public R accept(TreeVisitor visitor, D data) { return expression().accept(visitor, data); } @Override public Kind getKind() { return expression().getKind(); } @Override @Nullable protected Choice defaultAction(Tree tree, @Nullable Unifier unifier) { return Choice.condition(allowed().contains(tree.getKind()), unifier) .thenChoose(unifications(expression(), tree)); } } |
data class | 1. long method, 2. feature envy | t | t | f | 1. long method, 2. feature envy | data class | 0 | 988 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UOfKind.java/#L33-L64 | 2 | 58 | 988 | minor |
| 2622 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | Feature envy2 Long method | t | f | f | . Feature envy2. Long method | data class | 0 | 15059 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 2 | 2622 | 15059 | critical |
| 2698 | YES, I found bad smells! the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } } |
blob | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | blob | 0 | 15324 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 | 2 | 2698 | 15324 | minor |
| 2088 | {"response": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 13108 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 1 | 2088 | 13108 | minor |
| 2378 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | Long method, 2 Feature envy: | t | f | f | . Long method, 2. Feature envy: | data class | 0 | 14333 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 2 | 2378 | 14333 | minor |
| 3581 | of the below code has smelly codes No bad smells found. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | f | f | f | feature envy | 0 | 7900 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/service/cpi/SharingRegistryService.java/#L41810-L41827 | 2 | 3581 | 7900 | minor | ||
| 279 | YES I found bad smells the bad smells are: 1.Long method, 2.Inline code, 3.Poor naming convention | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Wrap extends DoFn> { @ProcessElement public void processElement(ProcessContext ctx) { ctx.output(KV.of(ctx.timestamp().getMillis(), ctx.element())); } } |
data class | Long method, 2Inline code, 3Poor naming convention | t | f | f | .Long method, 2.Inline code, 3.Poor naming convention | data class | 0 | 2988 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/euphoria/src/main/java/org/apache/beam/sdk/extensions/euphoria/core/translate/TimestampExtractTransform.java/#L78-L84 | 2 | 279 | 2988 | minor |
| 1057 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 9518 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 | 1 | 1057 | 9518 | minor |
| 2568 | YES I found bad smells The bad smells are: 1. Magic numbers (4, 0, 0, -length, i--) - these numbers are not descriptive and likely have specific meanings that should be extracted into named constants or variables. 2. Feature envy - the methods in the class seem to be more focused on manipulating the properties of the PlexOfCps and List objects, rather than actually representing or encapsulating the data. 3. Long method - the read() method spans over 50 lines and performs multiple operations. It could benefit from being broken up into smaller, more focused methods. 4. Code duplication - the writePlcfBkmkf() and writePlcfBkmkl() methods have similar code structures and could possibly be combined. 5. Missing encapsulation - the PlexOfCps and List objects are declared as public, which allows for direct access and manipulation from outside the class without any validation or control. These objects should be encapsulated and accessed through public methods. 6. Commented code - the "TODO: very non-optimal" comment indicates that there is potentially inefficient code that should be fixed, but it has not been addressed yet. Commented code can be misleading and creates clutter in the codebase. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } } |
blob | Magic numbers (4, 0, 0, -length, i--) - these numbers are not descriptive and likely have specific meanings that should be extracted into named constants or variables2 Feature envy - the methods in the class seem to be more focused on manipulating the properties of the PlexOfCps and List objects, rather than actually representing or encapsulating the data3 Long method - the read() method spans over 50 lines and performs multiple operations It could benefit from being broken up into smaller, more focused methods4 Code duplication - the writePlcfBkmkf() and writePlcfBkmkl() methods have similar code structures and could possibly be combined5 Missing encapsulation - the PlexOfCps and List objects are declared as public, which allows for direct access and manipulation from outside the class without any validation or control These objects should be encapsulated and accessed through public methods6 Commented code - the "TODO: very non-optimal" comment indicates that there is potentially inefficient code that should be fixed, but it has not been addressed yet Commented code can be misleading and creates clutter in the codebase | t | f | f | . Magic numbers (4, 0, 0, -length, i--) - these numbers are not descriptive and likely have specific meanings that should be extracted into named constants or variables.2. Feature envy - the methods in the class seem to be more focused on manipulating the properties of the PlexOfCps and List objects, rather than actually representing or encapsulating the data.3. Long method - the read() method spans over 50 lines and performs multiple operations. It could benefit from being broken up into smaller, more focused methods.4. Code duplication - the writePlcfBkmkf() and writePlcfBkmkl() methods have similar code structures and could possibly be combined.5. Missing encapsulation - the PlexOfCps and List objects are declared as public, which allows for direct access and manipulation from outside the class without any validation or control. These objects should be encapsulated and accessed through public methods.6. Commented code - the "TODO: very non-optimal" comment indicates that there is potentially inefficient code that should be fixed, but it has not been addressed yet. Commented code can be misleading and creates clutter in the codebase. | blob | 0 | 14874 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 | 2 | 2568 | 14874 | minor |
| 2538 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple calls to the same method with similar or duplicate values) 4. Inconsistent naming conventions (e.g. camelCase and snake_case being used interchangeably) 5. Use of deprecated libraries (e.g. RabbitManagementUtils) 6. Code complexity (e.g. nested if statements and loops) 7. Inconsistent use of braces (some methods have braces on separate lines, others have them on the same line) 8. Lack of proper error handling and exception throwing 9. Mixing logic and output/logging in the same method (e.g. doClean method) 10. Lack of documentation and comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } } |
blob | Long method2 Feature envy3 Duplicate code (multiple calls to the same method with similar or duplicate values)4 Inconsistent naming conventions (eg camelCase and snake_case being used interchangeably)5 Use of deprecated libraries (eg RabbitManagementUtils)6 Code complexity (eg nested if statements and loops)7 Inconsistent use of braces (some methods have braces on separate lines, others have them on the same line)8 Lack of proper error handling and exception throwing9 Mixing logic and output/logging in the same method (eg doClean method) | t | f | f | . Long method2. Feature envy3. Duplicate code (multiple calls to the same method with similar or duplicate values)4. Inconsistent naming conventions (e.g. camelCase and snake_case being used interchangeably)5. Use of deprecated libraries (e.g. RabbitManagementUtils)6. Code complexity (e.g. nested if statements and loops)7. Inconsistent use of braces (some methods have braces on separate lines, others have them on the same line)8. Lack of proper error handling and exception throwing9. Mixing logic and output/logging in the same method (e.g. doClean method) | blob | 0 | 14768 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 | 2 | 2538 | 14768 | minor |
| 415 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
data class | long method | t | t | f | long method | data class | 0 | 4221 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 1 | 415 | 4221 | major |
| 3774 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } } |
blob | data class, feature envy, long method | t | t | f | data class, feature envy, long method | blob | 0 | 9458 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 | 1 | 3774 | 9458 | minor |
| 1621 | YES I found bad smells. The bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class CounterMark { private final Row row; private final ColumnMetadata column; private final CellPath path; private CounterMark(Row row, ColumnMetadata column, CellPath path) { this.row = row; this.column = column; this.path = path; } public Clustering clustering() { return row.clustering(); } public ColumnMetadata column() { return column; } public CellPath path() { return path; } public ByteBuffer value() { return path == null ? row.getCell(column).value() : row.getCell(column, path).value(); } public void setValue(ByteBuffer value) { // This is a bit of a giant hack as this is the only place where we mutate a Row object. This makes it more efficient // for counters however and this won't be needed post-#6506 so that's probably fine. assert row instanceof BTreeRow; ((BTreeRow)row).setValue(column, path, value); } } |
data class | Long method, Feature envy | t | f | f | Long method, Feature envy. | data class | 0 | 11483 | https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/db/partitions/PartitionUpdate.java/#L661-L703 | 2 | 1621 | 11483 | minor |
| 692 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 6653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 692 | 6653 | minor |
| 4206 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
blob | data class | t | t | f | data class | blob | 0 | 11068 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 4206 | 11068 | minor |
| 2461 | YES I found bad smells the bad smells are: 1. Long Method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | Long Method | t | f | f | . Long Method | data class | 0 | 14541 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 2 | 2461 | 14541 | major |
| 1252 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | long method, feature envy | t | t | f | long method, feature envy | data class | 0 | 10442 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 2 | 1252 | 10442 | minor |
| 4852 | {"answer":"YES I found bad smells","detected_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 13206 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 | 1 | 4852 | 13206 | critical |
| 4138 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | blob, long method | t | t | f | blob, long method | data class | 0 | 10899 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 1 | 4138 | 10899 | major |
| 4574 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12157 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 2 | 4574 | 12157 | minor | ||
| 4353 | YES I found bad smells 1. Long method 2. Feature envy 3. Direct field access 4. Duplicate code 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | Long method2 Feature envy3 Direct field access4 Duplicate code5 Primitive obsession | t | f | f | . Long method2. Feature envy3. Direct field access4. Duplicate code5. Primitive obsession | blob | 0 | 11498 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 2 | 4353 | 11498 | minor |
| 2667 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long method", "2. Duplicate code"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
feature envy | 1. long method, 2. duplicate code | t | t | f | 1. long method, 2. duplicate code | feature envy | 0 | 15204 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 2667 | 15204 | major |
| 204 | {"message": "YES I found bad smells: the bad smells are: 1.Long method, 2.Magic number"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static final class XdrInputFormat extends PInputStream { private static final int READ_BUFFER_SIZE = 32 * 1024; private final class Buffer { private final byte[] buf; private int size; private int offset; Buffer(byte[] buf) { this.buf = buf; } int readInt() { return ((buf[offset++] & 0xff) << 24 | (buf[offset++] & 0xff) << 16 | (buf[offset++] & 0xff) << 8 | (buf[offset++] & 0xff)); } double readDouble() { long val = ((long) (buf[offset++] & 0xff) << 56 | (long) (buf[offset++] & 0xff) << 48 | (long) (buf[offset++] & 0xff) << 40 | (long) (buf[offset++] & 0xff) << 32 | (long) (buf[offset++] & 0xff) << 24 | (long) (buf[offset++] & 0xff) << 16 | (long) (buf[offset++] & 0xff) << 8 | buf[offset++] & 0xff); return Double.longBitsToDouble(val); } @SuppressWarnings("deprecation") String readString(int len) { /* * This fast path uses a cheaper String constructor if all incoming bytes are in the * 0-127 range. */ boolean fastEncode = true; for (int i = 0; i < len; i++) { byte b = buf[offset + i]; if (b < 0) { fastEncode = false; break; } } String result; if (fastEncode) { result = new String(buf, 0, offset, len); } else { result = new String(buf, offset, len, StandardCharsets.UTF_8); } offset += len; WeakReference entry; if ((entry = strings.get(result)) != null) { String string = entry.get(); if (string != null) { return string; } } strings.put(result, new WeakReference<>(result)); return result; } void readRaw(byte[] data) { System.arraycopy(buf, offset, data, 0, data.length); offset += data.length; } void readData(int n) throws IOException { if (offset + n > size) { if (offset != size) { // copy end piece to beginning System.arraycopy(buf, offset, buf, 0, size - offset); } size -= offset; offset = 0; while (size < n) { // read some more data int nread = is.read(buf, size, buf.length - size); if (nread <= 0) { throw RInternalError.unimplemented("handle unexpected eof"); } size += nread; } } } } /** * This buffer is used under normal circumstances, i.e. when the read data blocks are * smaller than the initial buffer. The ensureData method creates a special buffer for * reading big chunks of data exceeding the default buffer. */ private final Buffer defaultBuffer; private final WeakHashMap> strings = RContext.getInstance().stringMap; XdrInputFormat(InputStream is) { super(is); if (is instanceof PByteArrayInputStream) { // we already have the data and we have read the beginning PByteArrayInputStream pbis = (PByteArrayInputStream) is; defaultBuffer = new Buffer(pbis.getData()); defaultBuffer.size = pbis.getData().length; defaultBuffer.offset = pbis.pos(); } else { defaultBuffer = new Buffer(new byte[READ_BUFFER_SIZE]); defaultBuffer.size = 0; defaultBuffer.offset = 0; } } @Override int readInt() throws IOException { return ensureData(4).readInt(); } @Override double readDouble() throws IOException { return ensureData(8).readDouble(); } @Override String readString(int len) throws IOException { return ensureData(len).readString(len); } @Override void readRaw(byte[] data) throws IOException { ensureData(data.length).readRaw(data); } private Buffer ensureData(int n) throws IOException { Buffer usedBuffer; if (n > defaultBuffer.buf.length) { if (is instanceof PByteArrayInputStream) { // If the input stream is instance of PByteArrayInputStream, the buffer is // preloaded and thus no more data can be read beyond the current buffer. throw new IOException("Premature EOF"); } // create an enlarged copy of the default buffer byte[] enlargedBuf = new byte[n]; System.arraycopy(defaultBuffer.buf, defaultBuffer.offset, enlargedBuf, defaultBuffer.offset, defaultBuffer.size - defaultBuffer.offset); usedBuffer = new Buffer(enlargedBuf); usedBuffer.offset = defaultBuffer.offset; usedBuffer.size = defaultBuffer.size; // reset the default buffer defaultBuffer.offset = defaultBuffer.size = 0; usedBuffer.readData(n); // The previous statement should entirely fill the temporary buffer. // It is assumed that the caller will read n bytes, making the temporary buffer // disposable. Next time, the default buffer will be used again, unless // n > defaultBuffer.buf.length. assert usedBuffer.size == n; } else { usedBuffer = defaultBuffer; usedBuffer.readData(n); } return usedBuffer; } } |
blob | 1.long method, 2.magic number | t | t | f | 1.long method, 2.magic number | blob | 0 | 2291 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/RSerialize.java/#L1097-L1252 | 2 | 204 | 2291 | major |
| 1801 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SafeFileOutputStream extends FilterOutputStream { private final Path desiredFile; private Path tempFile; boolean desiredAlreadyExisted; public SafeFileOutputStream(Path file) throws IOException { this(file, tempFile(file)); } public SafeFileOutputStream(Path desiredFile, Path tempFile) throws IOException { super(Files.newOutputStream(tempFile)); this.desiredFile = desiredFile; this.tempFile = tempFile; // Some useful things to check that we preferably don't want to fail on // close() desiredAlreadyExisted = Files.exists(desiredFile); Path desiredFolder = this.desiredFile.getParent(); if (desiredAlreadyExisted) { if (!Files.isWritable(desiredFile)) { throw new FileNotFoundException("Can't write to " + desiredFile); } } else { if (!Files.exists(desiredFolder)) { throw new FileNotFoundException("Folder does not exist: " + desiredFolder); } if (!Files.isDirectory(desiredFolder)) { throw new FileNotFoundException("Not a directory: " + desiredFolder); } } if (!Files.isWritable(desiredFolder)) { throw new FileNotFoundException("Can't modify folder " + desiredFolder); } } private static Path tempFile(Path file) throws IOException { return Files.createTempFile(file.getParent(), file.getFileName() .toString(), ".tmp"); } @Override public void close() throws IOException { // If super.close fails - we leave the tempfiles behind super.close(); if (!Files.exists(tempFile)) { // Probably something went wrong before close called, // like rollback() return; } Path beforeDeletion = null; try { if (desiredAlreadyExisted) { // In case renaming goes wrong, we don't want to have already // deleted the // desired file. So we'll rename it to another temporary file // instead which // we can delete on successful rename. beforeDeletion = tempFile(desiredFile); if (!Files.deleteIfExists(beforeDeletion)) { // Should not happen, we just made it! throw new IOException("Can't delete temporary file " + beforeDeletion); } Files.move(desiredFile, beforeDeletion, StandardCopyOption.ATOMIC_MOVE); } try { Files.move(tempFile, desiredFile, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { // We'll leave our tempFiles for recovery. tempFile = null; beforeDeletion = null; if (Files.exists(desiredFile)) { // Someone else added or replaced the file afterwards, // kind-a OK return; } throw e; } } finally { if (beforeDeletion != null) { Files.deleteIfExists(beforeDeletion); } if (tempFile != null) { Files.deleteIfExists(tempFile); } } } public void rollback() throws IOException { super.close(); Files.deleteIfExists(tempFile); } } |
blob | t | f | f | blob | 0 | 12018 | https://github.com/apache/incubator-taverna-engine/blob/98536c6b702a0541debbb66be996455384561b54/taverna-prov/src/main/java/org/apache/taverna/prov/SafeFileOutputStream.java/#L36-L137 | 1 | 1801 | 12018 | minor | ||
| 2612 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | f | f | f | data class | 0 | 15042 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 2 | 2612 | 15042 | major | ||
| 2502 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | f | f | f | data class | 0 | 14662 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 2 | 2502 | 14662 | major | ||
| 2334 | NO, I did not find any bad smell | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | f | f | f | blob | 0 | 14160 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 2 | 2334 | 14160 | minor | ||
| 3 | {"response": "YES I found bad smells", "the bad smells are": "1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 554 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 2 | 3 | 554 | major |
| 28 | { "message": "NO, I did not find any bad smell" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 712 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 2 | 28 | 712 | critical | ||
| 974 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | data class | 0 | 8777 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 2 | 974 | 8777 | minor |
| 3368 | { "input_code": "public class Calculator {\n public int add(int a, int b) {\n return a + b;\n }\n\n public int subtract(int a, int b) {\n return a - b;\n }\n\n public int multiply(int a, int b) {\n return a * b;\n }\n}", "code_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
feature envy | f | f | f | Long Method, Data Class | false | 0 | 6394 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 3368 | 6394 | major | |
| 1631 | YES I found bad smells The bad smells are: 1. Long Method, 2. Feature Envy, 3. Inappropriate Intimacy, 4. Primitive Obsession, 5. Inconsistent Naming, 6. Data Class, 7. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } } |
blob | Long Method, 2 Feature Envy, 3 Inappropriate Intimacy, 4 Primitive Obsession, 5 Inconsistent Naming, 6 Data Class, 7 Long Parameter List | t | f | f | . Long Method, 2. Feature Envy, 3. Inappropriate Intimacy, 4. Primitive Obsession, 5. Inconsistent Naming, 6. Data Class, 7. Long Parameter List | blob | 0 | 11508 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 | 2 | 1631 | 11508 | minor |
| 788 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Feature envy 3. Long method 4. Data clumps 5. Lazy class 6. Shotgun surgery 7. Large class 8. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
data class | Duplicate code 2 Feature envy 3 Long method 4 Data clumps 5 Lazy class 6 Shotgun surgery 7 Large class 8 Inappropriate Intimacy | t | f | f | . Duplicate code 2. Feature envy 3. Long method 4. Data clumps 5. Lazy class 6. Shotgun surgery 7. Large class 8. Inappropriate Intimacy | data class | 0 | 7512 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 2 | 788 | 7512 | minor |
| 2016 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue.Builder public abstract static class Builder { public abstract Builder setCompileTimeConstant(boolean compileTimeConstant); public abstract Builder setStatic(boolean isStatic); public abstract Builder setFinal(boolean isFinal); public abstract Builder setVariableCapture(boolean isVariableCapture); public abstract Builder setEnclosingInstanceCapture(boolean isEnclosingInstanceCapture); public abstract Builder setEnclosingTypeDescriptor( DeclaredTypeDescriptor enclosingTypeDescriptor); public abstract Builder setName(String name); public abstract Builder setEnumConstant(boolean isEnumConstant); public abstract Builder setSynthetic(boolean isSynthetic); public abstract Builder setTypeDescriptor(TypeDescriptor typeDescriptor); public abstract Builder setVisibility(Visibility visibility); public abstract Builder setJsInfo(JsInfo jsInfo); public abstract Builder setUnusableByJsSuppressed(boolean isUnusableByJsSuppressed); public abstract Builder setDeprecated(boolean isDeprecated); public abstract Builder setOrigin(FieldOrigin fieldOrigin); public Builder setDeclarationFieldDescriptor(FieldDescriptor declarationFieldDescriptor) { return setDeclarationFieldDescriptorOrNullIfSelf(declarationFieldDescriptor); } // Accessors to support validation, default construction and custom setters. abstract Builder setDeclarationFieldDescriptorOrNullIfSelf( FieldDescriptor declarationFieldDescriptor); abstract Optional getName(); abstract FieldDescriptor autoBuild(); public FieldDescriptor build() { checkState(getName().isPresent()); FieldDescriptor fieldDescriptor = autoBuild(); checkState( !fieldDescriptor.isVariableCapture() || !fieldDescriptor.isEnclosingInstanceCapture()); return interner.intern(fieldDescriptor); } public static Builder from(FieldDescriptor fieldDescriptor) { return fieldDescriptor.toBuilder(); } private static final ThreadLocalInterner interner = new ThreadLocalInterner<>(); } |
blob | 1. long method | t | t | f | 1. long method | blob | 0 | 12770 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/ast/FieldDescriptor.java/#L194-L255 | 1 | 2016 | 12770 | minor |
| 40 | {"message": "YES I found bad smells. the bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
feature envy | 1. long method | t | t | f | 1. long method | feature envy | 0 | 769 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 2 | 40 | 769 | minor |
| 1770 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 11919 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 2 | 1770 | 11919 | major |
| 5 | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | f | f | f | long method | 0 | 565 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 1 | 5 | 565 | minor | |||
| 2469 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | Long method, 2Feature envy | t | f | f | .Long method, 2.Feature envy | data class | 0 | 14574 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 2 | 2469 | 14574 | major |
| 1978 | YES, I found bad smells: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy. | data class | 0 | 12631 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 2 | 1978 | 12631 | major |
| 2302 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Feature envy | t | f | f | . Feature envy | long method | 0 | 14043 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 2302 | 14043 | minor |
| 414 | YES I found bad smells The bad smells are: 1. Feature envy 2. Too many constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } } |
blob | Feature envy2 Too many constants | t | f | f | . Feature envy2. Too many constants | blob | 0 | 4220 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 | 2 | 414 | 4220 | major |
| 1414 | YES I found bad smells the bad smells are: 1. Singleton 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Singleton2 Feature envy | t | f | f | . Singleton2. Feature envy | data class | 0 | 10909 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 2 | 1414 | 10909 | major |
| 1643 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); } |
blob | Long Method, Data Class | t | f | f | Long Method, Data Class | blob | 0 | 11556 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 | 1 | 1643 | 11556 | critical |
| 186 | { "YES I found bad smells": "the bad smells are:", "Long method": true, "Feature envy": true } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. * * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} } |
blob | Incoherent response format, very different from what was expected. | t | t | f | the bad smells are: | blob | 0 | 2119 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 | 2 | 186 | 2119 | minor |
| 2552 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 14803 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 2552 | 14803 | minor |
| 2417 | {"response":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 14422 | https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 | 1 | 2417 | 14422 | major |
| 2125 | {"answer":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 13220 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 1 | 2125 | 13220 | major |
| 5298 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 14828 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 | 2 | 5298 | 14828 | major |
| 4370 | {"response":"YES I found bad smells","bad smells":["1. Long method","2. Long parameter list","3. Data class"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
blob | 1. long method, 2. long parameter list, 3. data class | t | t | f | 1. long method, 2. long parameter list, 3. data class | blob | 0 | 11535 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 2 | 4370 | 11535 | major |
| 1289 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Long method, 2 Feature envy | t | f | f | . Long method, 2. Feature envy | data class | 0 | 10615 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 2 | 1289 | 10615 | major |
| 879 | { "output": "YES, I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | long method, data class | t | t | f | long method, data class | feature envy | 0 | 8015 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 879 | 8015 | minor |
| 1255 | { "output": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | long method, feature envy | t | t | f | long method, feature envy | blob | 0 | 10491 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 2 | 1255 | 10491 | major |
| 1761 | { "output": "YES I found bad smells the bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | t | f | f | data class | 0 | 11891 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 1761 | 11891 | critical | ||
| 1375 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AttributeUtils { public static Attribute[] readAttributes(DataInputStream dataInputstream, ConstantPool cpool) { try { int length = dataInputstream.readUnsignedShort(); if (length == 0) { return Attribute.NoAttributes; } Attribute[] attrs = new Attribute[length]; for (int i = 0; i < length; i++) { attrs[i] = Attribute.readAttribute(dataInputstream, cpool); } return attrs; } catch (IOException e) { throw new ClassFormatException("IOException whilst reading set of attributes: " + e.toString()); } } /** Write (serialize) a set of attributes into a specified output stream */ public static void writeAttributes(Attribute[] attributes, DataOutputStream file) throws IOException { if (attributes == null) { file.writeShort(0); } else { file.writeShort(attributes.length); for (int i = 0; i < attributes.length; i++) { attributes[i].dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SIGNATURE) { return (Signature) attributes[i]; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_CODE) { return (Code) attributes[i]; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { return (ExceptionTable) attributes[i]; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { return (ConstantValue) attributes[i]; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { for (int i = 0; i < attributes.length; i++) { attributes[i].accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { return true; } } return false; } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { return (SourceFile) attributes[i]; } } return null; } } |
blob | data class, long method | t | t | f | data class, long method | blob | 0 | 10805 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java/#L9-L99 | 1 | 1375 | 10805 | major |
| 2464 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | long method | t | t | f | long method | data class | 0 | 14556 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 1 | 2464 | 14556 | major |
| 928 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | Long Method2 Feature Envy | t | f | f | . Long Method2. Feature Envy | data class | 0 | 8330 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 2 | 928 | 8330 | minor |
| 2434 | { "YES I found bad smells": "the bad smells are:", "Long method": "The method 'allocateLoadBalancerForNetwork' is too long and should be refactored into smaller methods", "Feature envy": "There are instances where an object envies the features of another object, indicating a potential design issue" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | Incoherent response format, very different from what was expected. | t | t | f | the bad smells are: | data class | 0 | 14462 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 2 | 2434 | 14462 | minor |
| 4631 | { "message": "NO, I did not find any bad smell" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | f | f | f | long method | 0 | 12359 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 4631 | 12359 | minor | ||
| 954 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | long method | t | t | f | long method | feature envy | 0 | 8530 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 954 | 8530 | minor |
| 2275 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
data class | 1. long method | t | t | f | 1. long method | data class | 0 | 13773 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 1 | 2275 | 13773 | minor |
| 3145 | YES I found bad smells The bad smells are: 1. Long method 2. No attributes 3. Feature envy 4. Use of raw types 5. Use of primitive type instead of objects 6. Code duplication 7. Lack of proper commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | Long method2 No attributes3 Feature envy4 Use of raw types5 Use of primitive type instead of objects6 Code duplication7 Lack of proper commenting/documentation | t | f | f | . Long method2. No attributes3. Feature envy4. Use of raw types5. Use of primitive type instead of objects6. Code duplication7. Lack of proper commenting/documentation | data class | 0 | 4282 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 2 | 3145 | 4282 | major |
| 921 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 8276 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 921 | 8276 | minor |
| 848 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } } |
blob | Long method 2 Feature envy | t | f | f | . Long method 2. Feature envy | blob | 0 | 7846 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 | 2 | 848 | 7846 | major |
| 1955 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } } |
blob | long method, data class | t | t | f | long method, data class | blob | 0 | 12554 | https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 | 1 | 1955 | 12554 | critical |
| 797 | { "input": { "codeSmells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "javaCode": "// Java code goes here" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": [ { "blob": false, "dataClass": false, "featureEnvy": true, "longMethod": true } ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: |
long method | message: yes i found bad smells, detectedcodesmells: blob: false, dataclass: false, featureenvy: true, longmethod: true | t | t | f | message: yes i found bad smells, detectedcodesmells: blob: false, dataclass: false, featureenvy: true, longmethod: true | long method | 0 | 7568 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 1 | 797 | 7568 | minor |
| 1015 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class KafkaTestServer { public static final int CACHE_TTL_MS = 1; private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestServer.class); private int kafkaPort = -1; private TestingServer zkServer; private KafkaServerStartable kafkaServer = null; private File sentrySitePath = null; public KafkaTestServer(File sentrySitePath) throws Exception { this.sentrySitePath = sentrySitePath; createZkServer(); this.kafkaPort = TestUtils.getFreePort(); createKafkaServer(); } public void start() throws Exception { kafkaServer.startup(); LOGGER.info("Started Kafka broker."); } public void shutdown() { if (kafkaServer != null) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); LOGGER.info("Stopped Kafka server."); } if (zkServer != null) { try { zkServer.stop(); LOGGER.info("Stopped ZK server."); } catch (IOException e) { LOGGER.error("Failed to shutdown ZK server.", e); } } } private Path getTempDirectory() { Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory("kafka-sentry-"); } catch (IOException e) { LOGGER.error("Failed to create temp dir for Kafka's log dir."); throw new RuntimeException(e); } return tempDirectory; } private void setupKafkaProps(Properties props) throws UnknownHostException { props.put("listeners", "SSL://" + InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort); props.put("log.dir", getTempDirectory().toAbsolutePath().toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controller.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", true); props.put("delete.topic.enable", false); props.put("controlled.shutdown.retry.backoff.ms", "100"); props.put("port", kafkaPort); props.put("offsets.topic.replication.factor", "1"); props.put("authorizer.class.name", "org.apache.sentry.kafka.authorizer.SentryKafkaAuthorizer"); props.put("sentry.kafka.site.url", "file://" + sentrySitePath.getAbsolutePath()); props.put("allow.everyone.if.no.acl.found", "true"); props.put("ssl.keystore.location", KafkaTestServer.class.getResource("/test.keystore.jks").getPath()); props.put("ssl.keystore.password", "test-ks-passwd"); props.put("ssl.key.password", "test-key-passwd"); props.put("ssl.truststore.location", KafkaTestServer.class.getResource("/test.truststore.jks").getPath()); props.put("ssl.truststore.password", "test-ts-passwd"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); props.put(KafkaAuthConf.KAFKA_SUPER_USERS, "User:CN=superuser;User:CN=superuser1; User:CN=Superuser2 "); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_ENABLE_NAME, "true"); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_TTL_MS_NAME, String.valueOf(CACHE_TTL_MS)); } private void createKafkaServer() throws UnknownHostException { Properties props = new Properties(); setupKafkaProps(props); kafkaServer = KafkaServerStartable.fromProps(props); } private void createZkServer() throws Exception { try { zkServer = new TestingServer(); } catch (Exception e) { LOGGER.error("Failed to create testing zookeeper server."); throw new RuntimeException(e); } } public String getBootstrapServers() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort; } } |
blob | Long method2 Feature envy | t | f | f | . Long method2. Feature envy | blob | 0 | 9297 | https://github.com/apache/sentry/blob/f859446b65bbc274bc4899464892151eec8217c6/sentry-tests/sentry-tests-kafka/src/main/java/org/apache/sentry/tests/e2e/kafka/KafkaTestServer.java/#L35-L129 | 2 | 1015 | 9297 | minor |
(3077 rows)